简体   繁体   中英

Two client sending message to server in java

This is a simple java program that sends a string from client to server and the server returns the length of the string to the client.

First, I run my server, and then I run a client, type in a string but not pressing Enter , then I run the 2nd client, type in a string and press Enter . Then the second client doesn't get a response until the first client's Enter is pressed. How can I solve that problem?

TCP Client

public class TCPClient {

    public static void main(String[] args) throws Exception {
        String sentence;
        String sentenceLength;

        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("mycomputer", 6789);

        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        sentenceLength = inFromServer.readLine();
        System.out.println(sentenceLength);

        clientSocket.close();
    }

}

TCP Server

public class TCPServer {

    public static void main(String[] args) throws Exception {
        String clientSentence;
        int clientSentenceLength;

        ServerSocket welcomeSocket = new ServerSocket(6789);

        while (true) {
            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            clientSentence = inFromClient.readLine();
            clientSentenceLength = clientSentence.length();
            outToClient.writeBytes(clientSentenceLength + "" + '\n');
        }
    }

}

As Martin Wickman has indicated in his comment, you need a separate thread. Here's what's happening.

Your server accepts a connection. It now won't do anything else until it has handled that connection.

So your client1 opens the connection to the server. This basically hogs the server (because the server isn't multithreaded or in any other way handling more than one client at a time). The server won't do anything else until it's done with client1.

To fix this, you need to create a thread to handle the client conversation. So your main loop accepts a fresh connection and feeds it to a brand new thread. That thread then handles that specific connection, and the main loop goes back to waiting for another client.

The server waits for the first client to send a sentence. This is the blocking line: clientSentence = inFromClient.readLine();

Only after the first client has send the message, the code will continue and only then the second client is actually handled by Socket connectionSocket = welcomeSocket.accept()

The way to solve is handle each client in its own thread. Simple raw untested example code:

public class ClientHandler implements Runnable {
    private Socket socket;
    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());

        clientSentence = inFromClient.readLine();
        clientSentenceLength = clientSentence.length();
        outToClient.writeBytes(clientSentenceLength + "" + '\n');

        socket.close();
    }
}

En then in the server, after you get the Socket from the accept() call you start a new Thread to handle the client:

    while (true) {
        Socket connectionSocket = welcomeSocket.accept();
        new Thread(new ClientHandler(connectionSocket)).start();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM