开发者

Should I have two threads for input/output or use NIO?

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");

            Buffe开发者_如何学JAVAredReader 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!


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜