Source of SocketClient.java


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