Socket
我用自己的电脑做服务端,又用自己的电脑做客户端。为什么在客户端输入的信息在服务端显示出来是乱码呢?新手刚学到这个,实在解决不了了!
代码:
package day06;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest04 {
private ServerSocket server;
public ServerTest04() {
try {
server = new ServerSocket(8088);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
System.out.println("等待连接……");
try {
Socket socket = server.accept();
System.out.println("一个服务器已连接!");
while(true){
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String str =reader.readLine();
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerTest04 server = new ServerTest04();
server.start();
}
}
package day06;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientTest04 {
private Socket socket;
public ClientTest04() {
try {
socket = new Socket("localhost", 8088);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
Scanner scanner = new Scanner(System.in);
OutputStream out;
try {
while(true){
out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
writer.println(scanner.nextLine());
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ClientTest04 client = new ClientTest04();
client.start();
}
}
Socket乱码