Net Serversocket Socket
# Java Example - ServerSocket and Socket Communication Example
[ Java Example](#)
The following example demonstrates how to implement a client sending a message to a server, the server receiving the message and reading the output, and then writing it back to the client, which receives the output.
### 1. Establish the Server Side
* The server establishes a communication ServerSocket.
* The server establishes a Socket to accept client connections.
* Establish an IO input stream to read data sent by the client.
* Establish 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(); }}}
Running the above code outputs:
Starting server....
### 2. Establish the Client
* Create Socket communication, setting the IP and Port of the communication server.
* Establish an IO output stream to send data messages to the server.
* Establish 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 to clientn"); 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(); }}}
Running the above code outputs:
Server: Testing client-server communication, server receives message and returns to client
[ Java Example](#)
YouTip