【发布时间】:2017-10-08 21:43:27
【问题描述】:
为了完全透明,这是一个作业。
还有更多工作要做,但目前我只是想获得以下内容:
- 节点 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 上看到的其他一些示例。
感谢您的所有帮助。我对套接字、端口、监听和其他方面非常不熟悉,所以如果我一开始不明白你的建议,请原谅我。我会尽我所能去理解它。
我没有添加整个代码,希望能使其更具可读性和明确问题所在,但如果您需要更多信息,请随时询问,我会尽力提供。
【问题讨论】:
-
1) 每次
ServerSocket.accept()返回时,您都会在服务器和客户端之间建立一个连接的套接字。对于 that 连接,您not 再次调用ServerSocket.accept()。 2) 在您的客户端中,PrintWriter 在内部缓冲数据。如果您希望在网络上立即看到调用out.print(line);的结果,那么您必须调用out.flush()作为下一条语句。 -
ready()所做的只是返回下一次读取是否会立即返回。见the documentation。
标签: java sockets bufferedreader java-threads