import java.net.*; import java.io.*; public class Server{ final static int serverPort = 8080; // server port number public static void main(String args[]) { ServerSocket sock = null; // server socket Socket clientSocket = null; // Client socket created by accept on Server side try{ sock = new ServerSocket(serverPort); // create socket and bind to port System.out.println("waiting for client to connect"); while(true) { clientSocket = sock.accept(); // wait for client to connect. Program will stuck on this statement until a client connects to the server multiThread mt = new multiThread(clientSocket); //creating a separate therad to handle the client socket mt.start(); //this starts the thread and calls run(). As a separate thread is launched, our loop continues and goes to sock.accept() //So now we have one thread( to handle client socket) running separately and this loop. // as clients keep coming in we will launch a separate thread for them } } catch(Throwable e) { // it's better to use try-catch in order to catch exceptions System.out.println("Error " + e.getMessage()); e.printStackTrace(); } //sock.close(); // I have commented sock.close() because I wanted my server to be always up. //You can set a condition to break the loop and then you should close the socket. } } class multiThread extends Thread //separate thread class to handle client socket { Socket clientSocket = null; // socket created by accept PrintWriter pw = null; // socket output stream for sending data to client BufferedReader br = null; // socket input stream for receiving data from client public multiThread(Socket s) //constructor for thread to set its client socket { clientSocket = s; } public void run() //this will be executed when mt.start() is called in other program { try{ System.out.println("client has connected"); pw = new PrintWriter(clientSocket.getOutputStream(),true); //creating PrintWriter over OutputStream br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //creating InputStreamReader over InputStream and Bufferreader over InputStreamReader String msg = br.readLine(); // read msg from client System.out.println("Message from the client > " + msg); pw.println("Got it!"); // send msg to client // close everything pw.close(); br.close(); clientSocket.close(); } catch (Throwable e) { System.out.println("Error " + e.getMessage()); e.printStackTrace(); } } }