我应该有两个线程用于输入/输出还是使用 NIO?
我一直在为我的网络课程开发一个(相对)简单的 TCP 客户端/服务器聊天程序。我遇到的问题是我正在使用阻塞调用,例如 read()
和 writeBytes()
。因此,每当我尝试向服务器发送消息时,服务器不会将其打印出来,直到它写回一条消息。对于这种情况,使用一个线程进行输入和一个线程进行输出是最明智的解决方案,还是使用 NIO 会更好?只是为了让您了解我的代码现在是什么样子,我的服务器是:
ServerSocket welcomeSocket = new ServerSocket(port);
DataOutputStream output;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(
System.in));
String sentence;
while ((sentence = inFromUser.readLine()) != null) {
Socket connectionSocket = welcomeSocket.accept();
output = new DataOutputStream( connectionSocket.getOutputStream());
output.writeBytes(sentence + "\n");
BufferedReader inFromServer = new BufferedReader( new InputStreamReader(
connectionSocket.getInputStream()));
System.out.println("Client said: " + inFromServer.readLine());
connectionSocket.close();
}
客户端代码本质上是相同的。感谢您抽出时间!
I have been working on a (relatively) simple tcp client/server chat program for my networking class. The problem that I am running into is I am using blocking calls, such as read()
and writeBytes()
. So, whenever I try to send a message to my server, the server does not print it out until it writes one back. For this situation, would using one thread for input and one thread for output be the most sensible solution, or would using NIO serve me better? Just to give you an idea of what my code looks like now, my server is:
ServerSocket welcomeSocket = new ServerSocket(port);
DataOutputStream output;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(
System.in));
String sentence;
while ((sentence = inFromUser.readLine()) != null) {
Socket connectionSocket = welcomeSocket.accept();
output = new DataOutputStream( connectionSocket.getOutputStream());
output.writeBytes(sentence + "\n");
BufferedReader inFromServer = new BufferedReader( new InputStreamReader(
connectionSocket.getInputStream()));
System.out.println("Client said: " + inFromServer.readLine());
connectionSocket.close();
}
The client code is essentially the same. Thanks for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非你想了解 NIO,否则就使用两个线程。 Java 教程提供了生成线程来处理与 ServerSocket 的客户端连接的示例。查看“写入套接字的服务器端”。
Just use two threads unless you want to learn about NIO. The Java tutorial has examples of spawning threads to handle client connections to a ServerSocket. Look toward the bottom of "Writing the Server Side of a Socket".