Create a server socket at port 12900, with 100 as the wait queue size at the localhost loopback address
ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost"));
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String argv[]) throws Exception { // create a server socket at port 6789 ServerSocket serverSocket = new ServerSocket(6789); // wait for incoming connection SOCKET PROGRAMMING 299 System.out.println("Server is listening on port 6789"); Socket serverEnd = serverSocket.accept(); System.out.println("Request accepted"); // get streams BufferedReader fromClient = new BufferedReader(new InputStreamReader(serverEnd.getInputStream())); PrintWriter toClient = new PrintWriter(serverEnd.getOutputStream(), true); // receive data from client int n = Integer.parseInt(fromClient.readLine()); System.out.println("Received from client: " + n); int fact = 1; for (int i = 2; i <= n; i++) fact *= i;/*from w w w .j a v a 2 s. c o m*/ // send result to the client toClient.println(fact); System.out.println("Sent to client: " + fact); serverSocket.close(); } }
The following code creates an Echo server.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String[] args) throws Exception { // Create a Server socket ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost")); System.out.println("Server started at: " + serverSocket); // Keep accepting client connections in an infinite loop while (true) { System.out.println("Waiting for a connection..."); // Accept a connection final Socket activeSocket = serverSocket.accept(); System.out.println("Received a connection from " + activeSocket); // Create a new thread to handle the new connection Runnable runnable = () -> { try {// ww w .j a va2s . c om handleClientRequest(activeSocket); } catch (Exception e) { e.printStackTrace(); } }; new Thread(runnable).start(); // start a new thread } } public static void handleClientRequest(Socket socket) throws Exception { BufferedReader socketReader = null; BufferedWriter socketWriter = null; // Create a buffered reader and writer for the socket socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String inMsg = null; while ((inMsg = socketReader.readLine()) != null) { System.out.println("Received from client: " + inMsg); // Echo the received message to the client String outMsg = inMsg; socketWriter.write(outMsg); socketWriter.write("\n"); socketWriter.flush(); } socket.close(); } }