Source of SocketServer.java


  1: //SocketServer.java
  2: 
  3: import java.util.Scanner;
  4: import java.io.InputStreamReader;
  5: import java.io.DataOutputStream;
  6: import java.io.PrintWriter;
  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("Waiting for a connection ...");
 22:             serverSocket = new ServerSocket(6789);
 23:             Socket socket = serverSocket.accept();
 24:             //Connection made, set up streams
 25:             inputStream = new Scanner(new
 26:                 InputStreamReader(socket.getInputStream()));
 27:             outputStream = new PrintWriter(new
 28:                 DataOutputStream(socket.getOutputStream()));
 29: 
 30:             //Read a line from the client
 31:             s = inputStream.nextLine();
 32: 
 33:             //Output text to the client
 34:             outputStream.print("Well, " + s + " is a ");
 35:             outputStream.println("fine programming language!");
 36:             outputStream.flush();
 37:             System.out.println("Closing " + s + " connection.");
 38:             inputStream.close();
 39:             outputStream.close();
 40:         }
 41:         catch (Exception e)
 42:         {
 43:             //If any exception occurs, display it
 44:             System.out.println("Error: " + e);
 45:         }
 46:     }
 47: }
 48: