项目中用到了Android和C++的通信。选择了用socket 发送字符的方式,一開始使用的代码是:
socket=new Socket(); InetSocketAddress isa = new InetSocketAddress(IP_STR, port); socket.connect(isa, 100); PrintWriter out=new PrintWriter(socket.getOutputStream(),true); BufferedReader recvBuf=new BufferedReader(new InputStreamReader(socket.getInputStream()));
使用这样的方式无法设定字符集,不管是发送和接收假设跟server的字符集不同,都会出现乱码,
最后将程序改为:
socket=new Socket(); InetSocketAddress isa = new InetSocketAddress(IP_STR, port); socket.connect(isa, 100); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"gb2312")),true); BufferedReader recvBuf=new BufferedReader(new InputStreamReader(socket.getInputStream(),"gb2312"));
我的server设定的字符集是gb2312。大家能够依据自己的须要设定字符集。原则是自己发送和对方接收的字符集设定要一致。自己的接收和对方的发送字符集一致。