出现乱码的代码:
/*使用子线程接收数据*/
new Thread(new Runnable() {
@Override
public void run() {
InputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
while (true) {
//接收服务端返回数据流
if (socket != null && socket.isConnected()) {
inputStream = socket.getInputStream();
if (inputStream == null) {
continue;
}
bufferedInputStream = new BufferedInputStream(inputStream);
byte[] bytes = new byte[1024];
int read = 0;
StringBuffer sb=new StringBuffer();
while((read = bufferedInputStream.read(bytes)) > -1){
String json = new String(bytes,"utf-8");
LogUtil.debug("socket接收到服务端返回的数据:" + json);
}
}
}
}
catch (IOException ex) {
try {
if (bufferedInputStream != null) bufferedInputStream.close();
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
日志调试输出,发现数据后面出现很多“�”乱码,如下图:
出现乱码的原因:
上面的代码使用byte字节分包接收数据,然后再进行中文转码,因为是使用字节流分包读取数据,所以在while()里转换编码是没有作用的,因为汉字会被拆分成2个字符,有可能放在不同的字节包里,编码转换就会失败。
解决乱码的方法:
在接收到socket数据时,通过子类InputStreamReader,OutputStreamWriter来转换编码,改进后的代码如下:
/*使用子线程接收数据*/
new Thread(new Runnable() {
@Override
public void run() {
InputStreamReader inputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
while (true) {
//接收服务端返回数据流
if (socket != null && socket.isConnected()) {
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
inputStream = new InputStreamReader(dataInputStream, charset);
if (inputStream == null) {
continue;
}
StringBuffer sb = new StringBuffer();
int count = 0;
char[] buf = new char[bytesize];
//一次性接收到所有数据,把每个包的字节拼接在一起,然后统一转为字符串
while ((count = inputStream.read(buf, 0, buf.length)) > -1) {
sb.append(buf, 0, count);
if (count < bytesize) {
break;
}
}
String data=sb.toString();
if(data.isEmpty()){
return;
}
LogUtil.debug("socket接收到服务端返回的数据:" + data);
}
}
}
catch (IOException ex) {
try {
if (bufferedInputStream != null) bufferedInputStream.close();
if (inputStream != null) {
inputStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
改进代码后,接收的socket数据没有出现乱码了,结果如下图: