A D
A D

Reputation: 809

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

            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!

Upvotes: 0

Views: 648

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128799

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

Upvotes: 1

Related Questions