最近在将一个项目由MyEclipse迁移到NetBeans的时候遇到乱码问题,该项目分为Web端工程和服务器端工程,Web端和服务器端通过Socket通信,之前两个工程都是放在MyEclipse中,通信都没有问题,但是我将两个工程迁移到Netbeans中再运行时发现Web程序乱码,经排查得出问题出在Socket通信过程中,至于是由Netbeans什么引起,还没有深入研究。
之前的Socket程序(客户端和服务器端)并没有指定特定的编码方式,代码如下:
服务器端:
1
PrintWriter l_out
=
new
PrintWriter(
new
BufferedOutputStream(socket.getOutputStream()));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
客户端:
1 PrintWriter l_out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()));
2 BufferedReader l_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
2 BufferedReader l_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
其中的socket是客户端的socket请求。
现改为
服务器端:
1
PrintWriter l_out
=
new
PrintWriter(
new
BufferedWriter(
new
OutputStreamWriter(s.getOutputStream(),
"
UTF-8
"
)));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(s.getInputStream(), " UTF-8 " ));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(s.getInputStream(), " UTF-8 " ));
客户端:
1
PrintWriter l_out
=
new
PrintWriter(
new
BufferedWriter(
new
OutputStreamWriter(s.getOutputStream(),
"
UTF-8
"
)));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(s.getInputStream(), " UTF-8 " ));
2 BufferedReader l_in = new BufferedReader( new InputStreamReader(s.getInputStream(), " UTF-8 " ));
其中的socket是客户端的socket请求。
后经过测试,客户端接收到的流解析出来不会出现乱码了。