首页 > 代码库 > android Socket通信
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();
android Socket通信