Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // DateServer.java
- // Acts as a server to give its local Date and Time.
- // Client must connect on the correct port.
- // Server closes the connection after send.
- //
- // Give the port number as a command line argument:
- // e.g. java DateServer 4567
- //
- import java.io.*;
- import java.net.*;
- import java.util.Date;
- public class DateServer {
- public final static int DEFAULT_PORT = 3456; // constants
- public final static int qLen = 5;
- private static ServerSocket listenSocket = null;
- private static OutputStreamWriter osw = null;
- public void DateServer() {} // Empty constructor!
- public static void main( String[] args) throws IOException {
- int portNum = DEFAULT_PORT;
- if( args.length != 0) {
- portNum = Integer.parseInt( args[ 0]);
- // put some test here to allow for port number not in range
- }
- try { // listen for clients and queue those that can’t be handled yet!
- listenSocket = new ServerSocket( portNum, qLen);
- }
- catch( BindException e) {
- System.err.println("Could not bind to port: " + portNum);
- System.err.println( "\tIs it already in use?");
- System.err.println( "\tIs it a reserved port number?");
- System.exit(1);
- }
- while( true) { // loop forever accepting clients from the queue
- Socket clientSocket = null;
- try { // talk to the client on a new socket
- clientSocket = listenSocket.accept();
- osw = new OutputStreamWriter( clientSocket.getOutputStream());
- // Might need to end previous line with , "US-ASCII"); or // "UTF-8");!
- Date date = new Date();
- // Why do we need to convert the date to a String?
- osw.write( date.toString()); // do we need + "\r\n");?
- osw.flush(); // make sure date got sent from the buffer!
- clientSocket.close();
- }
- catch( IOException ioE) {
- System.err.println( "Connection error, maybe the client died!");
- }
- finally { // to trap any other errors!!
- try {
- if( clientSocket != null) clientSocket.close();
- }
- catch( IOException ioE) {}
- } // end of finally
- } // while forever waiting for a client connection
- } // main
- } // class DateServer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement