首页 > 移动平台 > 详细

android Socket通信

时间:2014-09-22 11:57:13      阅读:251      评论:0      收藏:0      [点我收藏+]

实测:

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));

 

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

 

效果如下

bubuko.com,布布扣

 

 

方法二:

 

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();

android Socket通信

原文:http://www.cnblogs.com/gtgl/p/3985518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!