Java Sockets

Server Sockets

import java.net.*;
import java.io.*;
import java.util.Date;
 
public class DaytimeServer {

  //You need to be running as root to use ports < 1024.
  public final static int DEFAULT_PORT = 13;

  public static void main(String[] args) {

    int port = DEFAULT_PORT;     
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
        if (port < 0 || port >= 65536) {
          System.out.println("Port must between 0 and 65535");
          return;      
        }
      }   
      catch (NumberFormatException e) {
        // use default port
      }  

    }     

    try {

      //Create a server socket.
      ServerSocket server = new ServerSocket(port);

      //When someone connects we will have a socket.
      Socket connection = null;
      while (true) {
        
        try {
          connection = server.accept(); //blocks until someone connects.
          OutputStreamWriter out 
            = new OutputStreamWriter(connection.getOutputStream());
          Date now = new Date();
          out.write(now.toString() +"\r\n"); //write to it.
          out.flush();       //make sure we do write it all.
          connection.close();
        }
        catch (IOException e) {}
        finally {
          try {
            if (connection != null) connection.close();
          }
          catch (IOException e) {}          
        }
         
      }  // end while
       
    }  // end try
    catch (IOException e) {
      System.err.println(e);
    } // end catch

  } // end main

} // end DaytimeServer


José M. Vidal .

7 of 9