F
F
FLYABRWAY2016-11-22 15:24:14
Java
FLYABRWAY, 2016-11-22 15:24:14

How to implement the interaction (communication) of two clients on the server (JAVA)?

Hello! I am writing a program in which there is a server that waits for clients to connect and writes the Connection List of connected clients (sockets). It is necessary that the server then receives messages from one client and forwards to another client (defined). i.e. how to organize these working pairs? (client1-client2; client3-client4)

The client and server are written in Java...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ipc_ngs, 2016-11-22
@FLYABRWAY

In the main server thread, create a ServerSocket and call the bind() method to allow incoming connections on the appropriate port. Then, in a loop, you call the accept() method, which accepts an incoming connection from the next client and returns a Socket object. You call the getInputStream() and getOutputStrream() methods to get the input and output stream. Add this socket and its threads to your list of established connections, create a separate Thread object for the input stream of each new socket, and start it by calling start(). This thread in its run() method in a loop reads the data from the input stream, finds out to whom it needs to be passed, finds the corresponding socket in the list, and writes the data to its output stream. And so in the cycle reads / writes,
Thus, the main thread dynamically spawns parallel threads that serve incoming connections. It can do this in an infinite loop (until the server process is killed from the outside), or terminate itself according to some condition. If necessary, you can wait for all spawned threads to complete by calling their join() method.
With this approach, you need to remember to put the work with the list of sockets (adding, removing, searching) in a synchronized block to prevent collisions. You also need to write synchronized to the output stream if several clients can send data to the same destination.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question