简体   繁体   中英

Two clients communicate and exchange messages with server java socket

Sorry if its a duplicate question but I did not find the answer to my problem.

I have two clients A.java and B.java. How the server will know which of the two clients has sent a message without using Thread?

Server Code:

      try {

           ServerSocket ServerSocket=new ServerSocket(25000);
           System.out.println("Connect to the port 25000");

           while(true)
           {

               Socket socket=ServerSocket.accept();
               BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               String str = br.readLine();//msg from client A or B
               System.out.println(str);

           }
       }

       catch (Exception e)
       {
           System.out.println("Error");
       }

Client Code:( Both Clients have the same code in their class (ClientA.java or ClientB.java))

    try {
        Socket socket=new Socket("localhost",25000);

        DataOutputStream outToServer=new DataOutputStream(socket.getOutputStream());
        outToServer.writeBytes("Hello from ClientA" + '\n');(or Client B)

    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

You have at least one thread to get connections and one thread to receive messages. Otherwyse your application is blocked waiting for new connections and you can't do nothing else. But you don't need a thread for each client. If you add the socket to a list for each connected client you can loop through all client with a code similar to this one:

for (int i = 0; i < sockets.size(); i++) {
    try {
        Socket socket = sockets.get(i);
        if (socket.getInputStream().available() > 0) {
            // TODO: read data from socket
        }
    } catch (Exception e) {
        // TODO: Handle the exception
    }
}

You can use NIO with asynchronous capability.

On server side:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
serverSocketChannel.configureBlocking(false);
for (;;) {
    SocketChannel socketChannel = serverSocketChannel.accept();
    if (socketChannel != null){
      //here you can use socketChannel
    }
}

And on the clien side:

SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost", 8888));
while(! socketChannel.finishConnect() ){
    //wait here to finish and do something
}

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