gpt4 book ai didi

Java 套接字 - 读和写

转载 作者:行者123 更新时间:2023-12-03 01:02:34 24 4
gpt4 key购买 nike

问题:客户端没有收到任何消息。

这是客户端和服务器的完整代码:

客户

public class Client extends Socket{


public Client(String hostName, int port) throws UnknownHostException, IOException {
super(hostName,port);

BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream()));

while(true) {
String line = in.readLine();
System.out.println("Text received: " + line);
}

}

服务器

public final class Server extends ServerSocket{

public Server(int port) throws IOException {
super(port);

System.out.println("Server waiting for client 1");
Socket client1 = accept();
PrintWriter writer = new PrintWriter(client1.getOutputStream(), true);
writer.write("Hello user 1");

System.out.println("Server waiting for client 2");
Socket client2 = accept();
PrintWriter writer2 = new PrintWriter(client2.getOutputStream(), true);
writer2.write("Hello user 2");

System.out.println("Clients connected");

}
  • 我启动服务器来监听端口 4444
  • 我使用主机名“localhost”和端口 4444 启动客户端

最佳答案

您必须在消息末尾包含一个换行符,如果连接没有立即更改,还必须刷新 PrintWriter,强制自动刷新:

writer.write("Hello user 1\n");
writer.flush();

编辑:

可以使用构造函数在 PrintWriter 上启用自动刷新new PrintWriter(someOutputStream, true)

但是,正如文档中所解释的:

if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output

这意味着即使使用自动刷新,在调用 write 后仍需要手动刷新 PrintWriter,并且换行符 (\n) 仍将具有包含在字符串的末尾。

编辑2:

这是一个功能齐全的客户端/服务器应用程序的小示例:

客户:

public static void main(String[] args){
try{
Socket socket = new Socket(HOST_ADDRESS, PORT);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(bufferedReader.readLine());
bufferedReader.close();
socket.close();
}catch(IOException e){}
}

服务器:

public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write("Hello user!\n");
printWriter.flush();
printWriter.close();
socket.close();
serverSocket.close();
}catch(IOException e){}
}

关于Java 套接字 - 读和写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com