Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Implement a multi-threaded server program with Socket

Java Examples - Socket Multi-Threaded Server Program

Java Examples Java Examples

In Java, a multi-threaded server program can be implemented by using ServerSocket to listen for client connections and, whenever a new client connects, starting a new thread to handle that connection. Below is sample code showing how to implement a multi-threaded server program with Java Socket.

Server-side code

First, we create a server-side program that listens on a specified port and starts a new thread for each client connection to handle the communication.

MultiThreadedServer.java file

import

java

.

io

.*;

import

java

.

net

.*;

public

class

MultiThreadedServer

{

public

static

void

main

(

String

[

]

args

)

{

int

port

=

12345

;

//

Define the server port

try

(

ServerSocket

serverSocket

=

new

ServerSocket

(

port

)

)

{

System

.

out

.

println

(

"

Server started, waiting for client connections...

"

)

;

while

(

true

)

{

Socket

clientSocket

=

serverSocket

.

accept

(

)

;

//

Accept client connections

System

.

out

.

println

(

"

Client connected:

"

clientSocket

.

getInetAddress

(

)

.

getHostAddress

(

)

)

;

//

Start a new thread for each client connection

ClientHandler

clientHandler

=

new

ClientHandler

(

clientSocket

)

;

new

Thread

(

clientHandler

)

.

start

(

)

;

}

}

catch

(

IOException

e

)

{

e

.

printStackTrace

(

)

;

}

}

}

class

ClientHandler

implements

Runnable

{

private

Socket

clientSocket

;

public

ClientHandler

(

Socket

socket

)

{

this

.

clientSocket

=

socket

;

}

@

Override

public

void

run

(

)

{

try

(

InputStream

input

=

clientSocket

.

getInputStream

(

)

;

OutputStream

output

=

clientSocket

.

getOutputStream

(

)

;

BufferedReader

reader

=

new

BufferedReader

(

new

InputStreamReader

(

input

)

)

;

PrintWriter

writer

=

new

PrintWriter

(

output

,

true

)

)

{

String

clientMessage

;

while

(

(

clientMessage

=

reader

.

readLine

(

)

)

!=

null

)

{

System

.

out

.

println

(

"

Received client message:

"

clientMessage

)

;

writer

.

println

(

"

Server response:

"

clientMessage

)

;

//

Send the response message to the client

}

}

catch

(

IOException

e

)

{

e

.

printStackTrace

(

)

;

}

finally

{

try

{

clientSocket

.

close

(

)

;

}

catch

(

IOException

e

)

{

e

.

printStackTrace

(

)

;

}

}

}

}

Client code

The client code is used to connect to the server and send messages. You can create multiple clients to test the server's multi-threaded handling capability.

Client.java file code:

import

java.io.*

;

import

java.net.*

;

public

class

Client

{

   

public

static

void

main

(

String

[

]

args

)

{

       

String

serverAddress

=

"localhost"

;

       

int

port

=

12345

;

// Server port

       

try

(

Socket

socket

=

new

Socket

(

serverAddress, port

)

)

{

           

System

.

out

.

println

(

"Connected to server"

)

;

           

OutputStream

output

=

socket.

getOutputStream

(

)

;

           

PrintWriter

writer

=

new

PrintWriter

(

output,

true

)

;

           

InputStream

input

=

socket.

getInputStream

(

)

;

           

BufferedReader

reader

=

new

BufferedReader

(

new

InputStreamReader

(

input

)

)

;

           

BufferedReader

consoleReader

=

new

BufferedReader

(

new

InputStreamReader

(

System

.

in

)

)

;

           

String

userInput

;

           

while

(

(

userInput

=

consoleReader.

readLine

(

)

)

!=

null

)

{

                writer.

println

(

userInput

)

;

               

String

serverResponse

=

reader.

readLine

(

)

;

               

System

.

out

.

println

(

"Server response: "

serverResponse

)

;

           

}

       

}

catch

(

UnknownHostException

e

)

{

           

System

.

err

.

println

(

"Unknown host: "

serverAddress

)

;

            e.

printStackTrace

(

)

;

       

}

catch

(

IOException

e

)

{

           

System

.

err

.

println

(

"Unable to get I/O connection to: "

serverAddress

)

;

            e.

printStackTrace

(

)

;

       

}

   

}

}

Running steps

  1. Run the server side:

  2. Compile and run MultiThreadedServer class.
  3. The server will start and listen for client connections on the specified port.
  4. - Compile and run the `MultiThreadedServer` class. - The server will start and listen for client connections on the specified port.
    1. Run the client:

    2. Compile and run multiple Client class instances to simulate multiple clients connecting to the server.
    3. Enter messages in the client console; the client sends the message to the server and the server echoes the same message.
    4. - Compile and run multiple `Client` class instances to simulate multiple clients connecting to the server. - Enter messages in the client console; the client sends the message to the server and the server echoes the same message.

      Explanation

      This implementation ensures that the server can handle multiple client connections at the same time without blocking other clients' requests because of one client's long-running operation.

      Compile the code

      Open a terminal or command prompt, switch to the directory containing the above Java files, and then compile the code:

      
      
      javac MultiThreadedServer.java Client.java
      
      

      After compilation, run the server program first; the server will start and begin listening on port 12345.

      
      
      java MultiThreadedServer
      
      

      You will see the server output:

      
      
      服务器已启动,等待客户端连接...
      
      

      Open another terminal or command prompt window and run the client program. You can run multiple client instances to test multi-threaded handling.

      
      
      java Client
      
      

      You will see the client output:

      
      
      已连接到服务器
      
      

      Then you can enter a message in the client console, for example:

      
      
      Hello Server
      
      

      The server will respond:

      
      
      服务器回应: Hello Server
      
      

      The server-side output will show:

      
      
      客户端已连接: 127.0.0.1
      
      收到客户端消息: Hello Server
      
      

      Java Examples Java Examples