为了完全透明,这是一项作业。
还有更多工作要做,但目前我只是想实现以下目标:
- 节点A从文本文件读取
- 节点 A 使用套接字将文本文件(减去第一行)发送到节点 B
- 节点 B 从所述套接字读取数据,并将其打印到控制台
但是,现在看来,要么信息没有被发送,要么节点 B 没有正确读取信息。
在我的主类中,我设置了如下节点:
NodeA nodeA = new NodeA();
NodeB nodeB = new NodeB();
new Thread(nodeA).start();
new Thread(nodeB).start();
在节点 A 中,我这样做:
//Open a socket for talking with NodeB
Socket mySocket = new Socket(InetAddress.getLocalHost(), portNum);
//Set up the socket's output
PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
//Loop through the lines of the confA file, writing them to the socket
String line = bufferedReader.readLine();
while (line != null)
{
//Write the line to the socket, get the next line
out.println(line); //updated to println, this flushes and fixes another problem
out.flush();
line = bufferedReader.readLine();
}
//Close the socket
mySocket.close();
请注意,节点 A 的循环工作正常。当我使用 print 语句进行测试时,它不会永远循环,并且会遍历预期的文本行。
然后,在节点 B 端:更新以显示当前节点 B 代码
//Open the socket
ServerSocket mySocket = new ServerSocket(portNum);
Socket connectionSocket = mySocket.accept();
//Set up a reader on the socket to get what's coming from it
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String line = in.readLine(); //hang occurs here
while(line != null) {
System.out.println(line);
line = in.readLine();;
}
但是,in.ready() 从来都不是真的。我尝试使用 while 循环等待这种情况发生,但它从未发生。
我真的不知道为什么。我不知道我是否正确设置了套接字,是否正确设置了服务器,是否正确监听等等。
我只是认为将 B 设为监听 A 的服务器是最有意义的。我希望这是对的。它看起来与我在 SO 上看到的其他一些示例类似。
感谢您提供的所有帮助。我对套接字、端口、监听等非常不熟悉,所以如果我一开始不明白你的建议,请原谅我。我会尽力理解它。
我没有添加整个代码,希望使其更具可读性并更清楚地说明问题所在,但如果您需要更多信息,请随时询问,我会尽力提供。
最佳答案
服务器首先要从ServerSocket获取到客户端的Socket。
connectionSocket = mySocket.accept();
服务器线程将处于 sleep 状态,直到客户端使其接受 ConnectionSocket。
然后你就可以从connectionSocket中读取数据了。不需要准备
。
由于这是一项作业,剩下的就交给你了。
<小时/>顺便说一句,典型的服务器会这样做:
for (;;) {
Socket socket = serverSocket.accept();
... pass the socket to a thread from a pool of threads
}
关于java - 套接字的缓冲读取器从未准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46636366/