Java ServerSocket receive number value from client

Description

Java ServerSocket receive number value from client


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);
      while (true) {
         // wait for incoming connection
         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 ww  w  .j av a2  s .c  o  m*/
         // send result to the client
         toClient.println(fact);
         System.out.println("Sent to client: " + fact);
      }
   }
}



PreviousNext

Related