koutheir
koutheir

Reputation: 33

Multi-thread client socket in java

What's is the change that need to be done to a simple client socket writing in java to became a multi-thread socket .(i took a simple socket examle from the net) thank you

Upvotes: 0

Views: 585

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103893

Multi-thread.. client socket? That makes no sense. A single socket is a stream of data, you can't parallelize socket streams like this.

You can of course make an application that opens 5 separate connections (possibly all to the same server, that'd be fine), and processes these 5 separate connections, each consisting of a single stream of 'from client to server' bytes plus a single stream of 'from server to client' bytes, using 5 separate threads.

But you can't write an app that has a single connection, and then tries to process that connection using 5 threads.

Perhaps you meant server socket. For server sockets, you create a single ServerSocket object. A single thread calls the accept method on it (which waits for a client to connect, sets up the connection, and then hands you the Socket object that represents the single connection along with the 2 streams that form this connection). You can then make a new thread (or fetch a thread from a pool of threads, that's usually a better way to do this), hand it the socket, and let it deal with that socket. This way, you can have, say, 50 threads, each thread handling one socket: Your server can now deal with 50 clients all connecting simultaneously.

Upvotes: 3

Related Questions