java, 如何解决java socket中文乱码?不知道小伙伴们今天来看看边肖的分享吧!
您可以使用代码:
in=new BufferedReader(new InputStreamReader(socket.getInputStream(),UTF-8));
out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),UTF-8));
示例:
求解前:
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 {
//最多连接10次。
while(connects 10) {
connects++;
System.out.println( -等待连接- );
客户端套接字=服务器套接字。接受();//等待连接
System.out.println (the first connection and the second connection);
ServiceClient(clientSocket);
}
serverSocket.close();
} catch(IOException ioe) {
System.out.println(Error: + ioe);
}}
public static void ServiceClient(Socket client) throws IOException {
System.out.println(已链接);
InputStreamReader inSR=null;
OutputStreamWriter outSW=null;
try {
//读取数据
inSR=new InputStreamReader(client.getInputStream(), UTF-8);
BufferedReader br=new BufferedReader(inSR);
outSW=new OutputStreamWriter(client.getOutputStream(), UTF-8);
BufferedWriter bw=new BufferedWriter(outSW);
String str=;
while((str=br.readLine()) !=null) {
str=str.trim();
System.out.println(接收的客户端消息:str);
Bw.write(收到的消息:str/r/n);//将消息反馈给客户端,添加一个换行符让客户端接收。
bw.flush();
}
} finally {
//System.out.println(Cleaning up connection: + client);
inSR.close();
outSW.close();
client.close();
}
System.out.println(已断开);
}
}
解决后:
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());
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/r/n);//添加一个换行符,以便服务器逐行读取。
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最新内容,希望能帮到您!更多相关内容欢迎关注。