前言
在网络中传递中文字符有乱码是因为发送端编码和接收端解密不一致造成的。网络传递信息基本单元是字节,因此需要指定发送字节编码类型,如不指定默认为ISO-8859-1,接收端接收时,可以通过以下两种方式来保持编码一致性。
方法一
发送端可以使用DataOutputStream的writeUTF()方法发送信息,代码如下:
import java.io.BufferedOutputStream;@b@import java.io.DataOutputStream;@b@import java.net.Socket;@b@@b@public class SocketClientTest {@b@ public static void main(String[] args) throws Exception{@b@ Socket s=new Socket("localhost",8888);@b@ DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));@b@ dos.writeUTF("您好!");@b@ dos.flush();@b@ }@b@}
服务端使用DataInputStream的readUTF()方法接受内容,代码如下:
import java.io.BufferedInputStream;@b@import java.io.DataInputStream;@b@import java.net.ServerSocket;@b@import java.net.Socket;@b@@b@public class SocketServerTest {@b@@b@ public static void main(String[] args) throws Exception {@b@ @b@ ServerSocket ss=new ServerSocket(8888);@b@ System.out.println("server is started,waitting to connected...");@b@ Socket s=ss.accept();@b@ System.out.println("Client connection...");@b@ DataInputStream dis=new DataInputStream(new BufferedInputStream(s.getInputStream()));@b@ String receiveMsg=dis.readUTF();@b@ System.out.println("server has received word:"+receiveMsg);@b@ @b@ }@b@@b@}
运行结果:
server is started,waitting to connected...@b@Client connection...@b@server has received word:您好!
方法二
发送端使用Writer字符流发送内容,代码示例:
import java.io.OutputStreamWriter;@b@import java.io.PrintWriter;@b@import java.net.Socket;@b@@b@public class SocketClientTest2 {@b@ public static void main(String[] args) throws Exception{@b@ Socket s=new Socket("localhost",8888);@b@ OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream(),"UTF-8");@b@ PrintWriter pw=new PrintWriter(osw,true);@b@ pw.println("您好!");@b@ pw.close();@b@ }@b@}
import java.io.BufferedReader;@b@import java.io.InputStreamReader;@b@import java.net.ServerSocket;@b@import java.net.Socket;@b@@b@public class SocketServerTest2 {@b@ public static void main(String[] args) throws Exception {@b@ ServerSocket ss=new ServerSocket(8888);@b@ System.out.println("server is started,waitting to connected...");@b@ Socket s=ss.accept();@b@ System.out.println("Client connection...");@b@ InputStreamReader isr=new InputStreamReader(s.getInputStream(),"UTF-8");@b@ BufferedReader br=new BufferedReader(isr);@b@ String receiveMsg=br.readLine();@b@ System.out.println("server has received word:"+receiveMsg);@b@ @b@ }@b@}
运行结果:
server2 is started,waitting to connected...@b@Client connection...@b@server2 has received word:您好!
总结
在使用字符流发送和接受内容时,需要使用统一的编码格式,如上面使用”UTF-8“,当然也可以用"GBK“.