Source of SocketServer.java


  1: //SocketServer.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: import java.net.ServerSocket;
  9: 
 10: public class SocketServer
 11: {
 12:     public static void main(String[] args)
 13:     {
 14:         String s;
 15:         Scanner inputStream = null;
 16:         PrintWriter outputStream = null;
 17:         ServerSocket serverSocket = null;
 18:         try
 19:         {
 20:             // Wait for connection on port 6789
 21:             System.out.println("\nWaiting for a connection ...");
 22:             serverSocket = new ServerSocket(6789);
 23:             Socket socket = serverSocket.accept();
 24:             // Connection made, set up streams
 25:             inputStream =
 26:                 new Scanner
 27:                 (
 28:                     new InputStreamReader(socket.getInputStream())
 29:                 );
 30:             outputStream =
 31:                 new PrintWriter
 32:                 (
 33:                     new DataOutputStream(socket.getOutputStream())
 34:                 );
 35: 
 36:             // Read a line from the client
 37:             s = inputStream.nextLine();
 38: 
 39:             // Output text to the client
 40:             outputStream.print("\nWell, ");
 41:             outputStream.println(s + " is a fine programming language!");
 42:             outputStream.flush();
 43:             System.out.println("Closing connection from " + s);
 44:             inputStream.close();
 45:             outputStream.close();
 46:         }
 47:         catch (Exception e)
 48:         {
 49:             // If any exception occurs, display it
 50:             System.out.println("Error " + e);
 51:         }
 52:     }
 53: }
 54: