Java sockets: one server and multiple clients

So, I created a basic client-server program in Java. It starts as follows:

  • Client connects to server
  • Server asks for client name
  • Customer responds with a name
  • The server greets the client
  • After that, the Client speaks and the Server repeats the words back

I got this to work without any problems using this tutorial . The problem occurs when I try to implement multiple clients. I thought this would work, because I use several threads, however, other clients just hang until the first client closes, and then it starts its work (the server accepts input from the second client, but does not answer everything, until until the first client completes).

Here is the code I'm using:

import java.net.*; import java.io.*; public class Server extends Thread { private ServerSocket listener; public Server(int port) throws IOException { listener = new ServerSocket(port); } public void run() { while(true) { try { Socket server = listener.accept(); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("What is your name?"); DataInputStream in = new DataInputStream(server.getInputStream()); String user_name = in.readUTF(); out.writeUTF("Hello "+user_name); while(true) { String client_message = in.readUTF(); out.writeUTF(client_message); } } catch(IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { int port = 6006; try { Thread t = new Server(port); t.start(); } catch(IOException e) { e.printStackTrace(); } } } 

Can someone explain what I'm doing wrong?

I looked at using Runnable instead of Extends Thread, but I had even more problems, so I want to try and work with this first.

+6
source share
2 answers

Incoming connections are processed only by the string listener.accept(); . But after you connected the client, you are stuck in a while loop. You need to create a new Thread (or Runnable executed on an ExecutorService if you expect a high load) and start it, and then immediately accept the following connection.

+4
source

In short, this is what goes wrong.

  • You use only one thread as a server.
  • Blocking this topic when calling listener.accept ()

This is what you need to do:

Create two classes 1: Server. Similar to what you have now, but instead of doing the actual work as an echo server, it just spawns a new thread that starts listening on the new port (which you can choose arbitrarily) and sends the client the address for this new port. Then the client will receive a new port number and try to connect to the server on the new port. 2: Echo stream - launches a new listener on the transmitted port and echoes the listener.

OR

You are starting a UDP server, not a TCP server, and all this does not matter, but it is beyond the scope of this particular issue.

+3
source

Source: https://habr.com/ru/post/953016/


All Articles