Source of SocketClient.java


  1: import java.util.Scanner;
  2: import java.io.InputStreamReader;
  3: import java.io.DataOutputStream;
  4: import java.io.PrintWriter;
  5: import java.net.Socket;
  6: 
  7: public class SocketClient
  8: {
  9:  public static void main(String[] args)
 10:  {
 11:   String s;
 12:   Scanner inputStream = null;
 13:   PrintWriter outputStream = null;
 14:   try
 15:   {
 16:    // Connect to server on same machine, port 6789
 17:    Socket clientSocket = new Socket("localhost",6789);
 18:    // Set up streams to send/receive data
 19:    inputStream = new Scanner(new InputStreamReader(clientSocket.getInputStream()));
 20:    outputStream = new PrintWriter(new DataOutputStream(clientSocket.getOutputStream()));
 21: 
 22:    // Send "Java" to the server
 23:    outputStream.println("Java");
 24:    outputStream.flush(); // Sends data to the stream
 25: 
 26:    // Read everything from the server until no more lines
 27:    // and output it to the screen
 28:    while (inputStream.hasNextLine())
 29:    {
 30:      s = inputStream.nextLine();
 31:      System.out.println(s);
 32:    }
 33:    inputStream.close();
 34:    outputStream.close();
 35:   }
 36:   catch (Exception e)
 37:   {
 38:    // If any exception occurs, display it
 39:    System.out.println("Error " + e);
 40:   }
 41:  }
 42: }