简体   繁体   中英

Creating a socket server and client which allows multiple connections via threads and Java

I am trying to make a simple socket server so that it can have multiple TCP connections, via multithreading, but I can't seem to get it to work. It works for 1 client but i can't connect another client. I am new to this and any help would be appreciated.

public class Client {

public static void main(String argv[]) throws Exception {
    String sentence;
    String modifiedSentence;

    BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
    Socket clientSocket = new Socket("localhost", 6789);

    while (true) {
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        if (sentence.equalsIgnoreCase("EXIT")) 
        {
            break;
        }
        else if (sentence.equalsIgnoreCase("i am the boss"))
        {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            Thread.currentThread().setName("boss");
            System.out.println("You have top priority boss");
        }
        else if(sentence!=null)
        {
            System.out.println("running thread name is:"+Thread.currentThread().getName());  
            System.out.println("running thread priority is:"+Thread.currentThread().getPriority());  
        }
        modifiedSentence = inFromServer.readLine();
        System.out.println("server : " + modifiedSentence);
    }
    clientSocket.close();
}


public class Server {

    public static void main(String argv[]) throws Exception {

        ServerSocket welcomeSocket = new ServerSocket(6789);
        Responder h = new Responder();
        while (true) {

            Socket connectionSocket = welcomeSocket.accept();
            Thread t = new Thread(new MyServer(h, connectionSocket));

            t.start();
        }
    }
}

class MyServer implements Runnable {

        Responder h;
        Socket connectionSocket;

        public MyServer(Responder h, Socket connectionSocket) {
            this.h = h;
            this.connectionSocket = connectionSocket;
        }

        @Override
        public void run() {

            while (h.responderMethod(connectionSocket)) {
                try 
                {
                    Thread.sleep(5);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }

            try {
                connectionSocket.close();
            } catch (IOException ex) {
                Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

}

class Responder {

    String serverSentence;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    synchronized public boolean responderMethod(Socket connectionSocket) {
        try {
            BufferedReader inFromClient =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient =  new DataOutputStream(connectionSocket.getOutputStream());
            String clientSentence = inFromClient.readLine();

            if (clientSentence.equalsIgnoreCase("EXIT")) {
                return false;
            }

            if (clientSentence != null) {
                System.out.println("client : " + clientSentence );


            }

            serverSentence = br.readLine() + "\n";
            outToClient.writeBytes(serverSentence);
            return true;

        } catch (SocketException e) {
            System.out.println("Disconnected");
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

What exactly is happening:

  1. Server creates ServerSocket and keeps listening for client request
  2. A Client1 sends a request and server accepts it, creating an object of Reponder and passing it to a separate MyServer Thread.
  3. The server starts listening for another client request on ServerSocket & the thread also waits for an input from the Client1 . This leads to the thread holding a lock on the Responder object.
  4. A new client Client2 connects to Server. request is accepted on ServerSocket and the same object of Responder is passed to a separate thread to handle Client2 request.

Remember: The lock is still held on the Responder object by thread1

Thus, unless Client1 sends some data to the Server , the lock will exist. Once the Client1 data is received by the server, the Responder object becomes available to the thread2 and now its execution can begin.

But hold on, Client1 still expects some data in return from the Server . Thus, even if Client2 sends its data to server, the server won't reply to it unless it replies back to Client1 first.

This leads to a situation where at a time only single Client-Server communication is observed.


Alternatively, you can create separate objects of the responder class to handle each client request.

You can put the separated statement (below) inside the while loop:

public class Server {

    public static void main(String argv[]) throws Exception {

        ServerSocket welcomeSocket = new ServerSocket(6789);

        Responder h = new Responder();

        while (true) {

            Socket connectionSocket = welcomeSocket.accept();
            Thread t = new Thread(new MyServer(h, connectionSocket));

            t.start();
        }
    } }

This will create a separate responder for each client request and ultimately multiple client requests would be handled by the server, and observable too. :D

NOTE: Your code will flawlessly work given there are continuous client requests coming and the server keeps replying to them.

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