本帖最后由 ppgjx 于 2023-1-20 17:21 编辑
服务器端
[Asm] 纯文本查看 复制代码 public static void main(String[] args) throws IOException {
// 监听本地主机的端口 8000
ServerSocket serverSocket = new ServerSocket(1316);
System.[i]out[/i].println("Server started, waiting for client to connect...");
// 等待客户端连接
while (true) {
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.[i]out[/i].println("Client connected from " + clientSocket.getInetAddress());
// 获取输入流并读取客户端发送的信息
InputStream in = clientSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = in.read(buffer);
String message = new String(buffer, 0, bytesRead);
System.[i]out[/i].println("Received from client: " + message);
// 关闭连接
in.close();
clientSocket.close();
}
}
客户端
[Asm] 纯文本查看 复制代码 public static void main(String[] args) throws IOException {
// 监听本地主机的端口 8000
Socket socket = new Socket("127.0.0.1", 1316);
while (true){
// 获取输出流并写入要发送给服务端的信息
OutputStream out = socket.getOutputStream();
Scanner sc = new Scanner(System.[i]in[/i],"UTF-8");
System.[i]out[/i].println("play input");
String s = sc.nextLine();
out.write(s.getBytes());
out.flush();
// out.close();
// 关闭连接
}
}
然后我输入三次1就出错了 异常还是乱码 有人知道是咋回事吗 谢谢
[Asm] 纯文本查看 复制代码 play input
1
play input
1
play input
1
Exception in thread "main" java.net.SocketException: ��������е������ֹ��һ���ѽ��������ӡ�
at java.base/sun.nio.ch.NioSocketImpl.implWrite(NioSocketImpl.java:413)
at java.base/sun.nio.ch.NioSocketImpl.write(NioSocketImpl.java:433)
at java.base/sun.nio.ch.NioSocketImpl$2.write(NioSocketImpl.java:812)
at java.base/java.net.Socket$SocketOutputStream.write(Socket.java:1120)
at java.base/java.io.OutputStream.write(OutputStream.java:124)
at ClientTest.main(ClientTest.java:21)
与目标 VM 断开连接, 地址为: ''127.0.0.1:6162',传输: '套接字'' |