码迷,mamicode.com
首页 > 移动开发 > 详细

android Socket通信

时间:2014-09-22 13:06:02      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:android   http   os   ar   div   sp   art   问题   on   

实测:

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通信

标签:android   http   os   ar   div   sp   art   问题   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!