android socket 通讯(客户端) 发送数据
Posted 风雪江山
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android socket 通讯(客户端) 发送数据相关的知识,希望对你有一定的参考价值。
/** ClientSocket通讯类 **/
public class ClientSocket {
/**服务器地址*/
private String serverUrl="192.168.124.214";
/**服务器端口*/
private int serverPort=8888;
/*发送命令线程*/
class sendCommandThread extends Thread{
private String command;
public sendCommandThread(String aCommand){
this.command = aCommand;
}
public void run(){
try{
Socket socket = new Socket(serverUrl,serverPort);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(command);
out.flush();
}catch (UnknownHostException e){
}catch (IOException e){
}
}
}
/** 发送文件线程 **/
class sendFileThread extends Thread{
private byte byteBuffer[] = new byte[1024];
private OutputStream outsocket;
private ByteArrayOutputStream myOutputStream;
public sendFileThread(ByteArrayOutputStream myOutputStream) {
this.myOutputStream = myOutputStream;
try {
myOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
try {
Socket socket = new Socket(serverUrl,serverPort);
outsocket = socket.getOutputStream();
//写入头信息
String msg = java.net.URLEncoder.encode("PHONEVIDEO","utf-8");
byte[] buffer = msg.getBytes();
outsocket.write(buffer);
ByteArrayInputStream inputStream = new ByteArrayInputStream(myOutputStream.toByteArray());
int amount;
while ((amount = inputStream.read(byteBuffer))!= -1) {
outsocket.write(byteBuffer,0,amount);
}
myOutputStream.flush();
myOutputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是关于android socket 通讯(客户端) 发送数据的主要内容,如果未能解决你的问题,请参考以下文章
Android Socket通讯 分离服务端和客户端发送表情消息