欢迎光临
我们一直在努力

java socket乱码

java socket乱码插图

java socket乱码

解决方法:

首先在服务端使用InputStreamReader指定客户端的输入流为utf-8编码,以及使用OutputStreamWriter指定输出流为utf-8编码;

然后在客户端同样的设置utf-8编码即可。

in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));

示例:

Server:

import java.io.*;
import java.net.*;
 
public class SocketServerEx1 {
	public static void main(String args[]) {
		System.out.println("Server");
		
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		int connects = 0;
		try {
			serverSocket = new ServerSocket(82, 5);		//端口:82,最大链接数:5
 
			//最多连接10次
			while(connects 

Client:

import java.io.*;
import java.net.*;
 
public class SocketClientEx1 {
	public static void main(String[] args) {
		System.out.println("Client");
		try {
			Socket clientSocket = new Socket("localhost", 82);
			System.out.println("Client1:" + clientSocket);
 
			DataInputStream dataIS = new DataInputStream(clientSocket.getInputStream());
			InputStreamReader inSR = new InputStreamReader(dataIS, "UTF-8");
			BufferedReader br = new BufferedReader(inSR);
			
			DataOutputStream dataOS = new DataOutputStream(clientSocket.getOutputStream());
			OutputStreamWriter outSW = new OutputStreamWriter(dataOS, "UTF-8");
			BufferedWriter bw = new BufferedWriter(outSW);
 
			//输入信息
			byte bytes[] = new byte[100];
			while(true) {
				System.out.println("----------------------------------");
				System.in.read(bytes);
				String str = new String(bytes);
				str = str.trim();
				if (str == "exit") {
					break;
				}
 
				//发送数据
				bw.write(str + "
");		//加上分行符,以便服务器按行读取
				bw.flush();
				
				
				//接收数据
				while((str = br.readLine()) != null) {
					str = str.trim();
					System.out.println("服务器回复:" + str);
					break;
				}
 
			}
			
			inSR.close();
			dataIS.close();
			dataOS.close();
			clientSocket.close();
		} catch(UnknownHostException uhe) {
			System.out.println("Error:" + uhe.getMessage());
		} catch(ConnectException ce) {
			System.out.println("Error:" + ce.getMessage());
		} catch(IOException ioe) {
			System.out.println("Error:" + ioe.getMessage());
		} finally {
		}
	}
}

云海天教程网,大量的免费Java入门教程,欢迎在线学习!

相关推荐: java中中文乱码怎么解决?

java中中文乱码解决方法: 一、设置工作空间的编码 1、编辑器的编码会影响到所有的项目中的字符的显示,可以说是作用最为广泛的设置,每一个项目都会受到这个设置的影响。点击菜单栏中的窗口(Window)— —选项(Preferences)。 2、点击常规(Gen…

赞(0)
未经允许不得转载:爱分享 » java socket乱码

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

爱分享,生活常用知识教程百科分享、学习、交流平台

爱分享精选好货商城