java socket出错请教
本帖最后由 ppgjx 于 2023-1-20 17:21 编辑服务器端
public static void main(String[] args) throws IOException {
// 监听本地主机的端口 8000
ServerSocket serverSocket = new ServerSocket(1316);
System.out.println("Server started, waiting for client to connect...");
// 等待客户端连接
while (true) {
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected from " + clientSocket.getInetAddress());
// 获取输入流并读取客户端发送的信息
InputStream in = clientSocket.getInputStream();
byte[] buffer = new byte;
int bytesRead = in.read(buffer);
String message = new String(buffer, 0, bytesRead);
System.out.println("Received from client: " + message);
// 关闭连接
in.close();
clientSocket.close();
}
}
客户端
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.in,"UTF-8");
System.out.println("play input");
String s = sc.nextLine();
out.write(s.getBytes());
out.flush();
// out.close();
// 关闭连接
}
}
然后我输入三次1就出错了 异常还是乱码 有人知道是咋回事吗 谢谢
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',传输: '套接字'' 兄弟你这两个while位置不对 你百度echo sever照着改改
页:
[1]