Java Examples - ServerSocket and Socket Communication Example
The following example demonstrates how the client sends a message to the server, the server receives the message and reads the output, then writes it to the client, and the client receives the output.
1. Set up the server side
- The server establishes a communication ServerSocket
- The server creates a Socket to accept client connections
- Create an IO input stream to read data sent by the client
- Create an IO output stream to send data messages to the client
Server-side code:
Server.java file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("Starting the server....");
Socket s = ss.accept();
System.out.println("Client:"+s.getInetAddress().getLocalHost()+"Connected to the server");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//Read the message sent by the client
String mess = br.readLine();
System.out.println("Client:"+mess);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(mess+"\n");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output of running the above code is:
Start server....
2. Set up the client side
- Create Socket communication, set the IP and Port of the communication server
- Create an IO output stream to send data messages to the server
- Create an IO input stream to read data messages sent by the server
Client-side code:
Client.java file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",8888);
//Build IO
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
//Send a message to the server side
bw.write("Test the communication between client and server; the server receives the message and returns it to the client\n");
bw.flush();
//Read the message returned by the server
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String mess = br.readLine();
System.out.println("Server:"+mess);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output of running the above code is:
Server: Testing communication between client and server; the server receives the message and returns it to the client.Other Extensions