android Socket通信

实测:

Socket socket = new Socket(ip, InterNetConfig.MORNITORPORT);
// 向服务器发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),InterNetSendThread.STREAM_DECODE_MODE)),true);
out.println(msg);

System.out.println(TAG+"end writer to ip = "+ip);
// 从服务器获取返回消息
BufferedReader readBuffer = new BufferedReader(new InputStreamReader(socket.getInputStream(), InterNetSendThread.STREAM_DECODE_MODE));
res = readBuffer.readLine();

参考:

方法一:

 

主要还是服务器端和客户端编码匹配的问题

不管用何种编码

只要两端匹配

就ok

不要假定默认编码

一个个去试

不如一行code

 

关键代码

public static final String bm="GBK"; //全局定义,以适应系统其他部分

 

InputStream is;
BufferedReader br;

bw = new BufferedWriter(new OutputStreamWriter(os,bm));
br = new BufferedReader(new InputStreamReader(is,bm));

bw.write(msg);

 

Msg = new String(b,bm);

 

OutputStream os = socket.getOutputStream();
os.write(str.getBytes(bm));

 

整个工程中和编码相关的部分如上所示

 

效果如下

 

 

方法二:

 

1.服务器端输出时:

 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true);

2.客户端接收时:

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),"UTF-8"));

String read = in.readLine();

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。