我应该有两个线程用于输入/输出还是使用 NIO?

发布于 2024-12-08 00:45:08 字数 1005 浏览 4 评论 0原文

我一直在为我的网络课程开发一个(相对)简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南城追梦 2024-12-15 00:45:08

除非你想了解 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".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文