Java Socket send to and receive from server

Description

Java Socket send to and receive from server

 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {
   public static void main(String argv[]) throws Exception {
      String fact;//  w  ww .j av a2s.  c om
      // create a socket to the server
      Socket clientEnd = new Socket("localhost", 6789);
      System.out.println("connected to localhost at port 6789");
      // get streams
      PrintWriter toServer = new PrintWriter(clientEnd.getOutputStream(), true);
      BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientEnd.getInputStream()));
      BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
         // get an integer from user
         System.out.print("Enter an integer: ");
         String n = fromUser.readLine();
         // send it to server
         toServer.println(n);
         System.out.println("Sent to server: " + n);
         if (n.equals("-1"))
            break;
         // retrieve result
         fact = fromServer.readLine();
         System.out.println("Received from server: " + fact);
      }
      // close the socket
      clientEnd.close();
   }
}



PreviousNext

Related