Java Example - ServerSocket and Socket Communication Example
The following example demonstrates how to implement a client sending a message to a server, the server receiving and reading the message, and then sending it back to the client who receives the output.
1. Set up the server side
- Establish communication with ServerSocket
- Set up a Socket to receive 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 server....");
Socket s = ss.accept();
System.out.println("Client:" + s.getInetAddress().getLocalHost() + " has 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 the above code is:
Starting server....
2. Set up the client side
- Create a Socket for communication, set the IP and Port of the 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
bw.write("Testing client-server communication, server receives message and returns it to 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 above code outputs:
Server: Testing client-server communication, the server receives the message and returns it to the client