Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. //
  2. // DateServer.java
  3. // Acts as a server to give its local Date and Time.
  4. // Client must connect on the correct port.
  5. // Server closes the connection after send.
  6. //
  7. // Give the port number as a command line argument:
  8. // e.g. java DateServer 4567
  9. //
  10. import java.io.*;
  11. import java.net.*;
  12. import java.util.Date;
  13. public class DateServer {
  14. public final static int DEFAULT_PORT = 3456; // constants
  15. public final static int qLen = 5;
  16. private static ServerSocket listenSocket = null;
  17. private static OutputStreamWriter osw = null;
  18. public void DateServer() {} // Empty constructor!
  19. public static void main( String[] args) throws IOException {
  20. int portNum = DEFAULT_PORT;
  21. if( args.length != 0) {
  22. portNum = Integer.parseInt( args[ 0]);
  23. // put some test here to allow for port number not in range
  24. }
  25. try { // listen for clients and queue those that can’t be handled yet!
  26. listenSocket = new ServerSocket( portNum, qLen);
  27. }
  28. catch( BindException e) {
  29. System.err.println("Could not bind to port: " + portNum);
  30. System.err.println( "\tIs it already in use?");
  31. System.err.println( "\tIs it a reserved port number?");
  32. System.exit(1);
  33. }
  34. while( true) { // loop forever accepting clients from the queue
  35. Socket clientSocket = null;
  36. try { // talk to the client on a new socket
  37. clientSocket = listenSocket.accept();
  38. osw = new OutputStreamWriter( clientSocket.getOutputStream());
  39. // Might need to end previous line with , "US-ASCII"); or // "UTF-8");!
  40. Date date = new Date();
  41. // Why do we need to convert the date to a String?
  42. osw.write( date.toString()); // do we need + "\r\n");?
  43. osw.flush(); // make sure date got sent from the buffer!
  44. clientSocket.close();
  45. }
  46. catch( IOException ioE) {
  47. System.err.println( "Connection error, maybe the client died!");
  48. }
  49. finally { // to trap any other errors!!
  50. try {
  51. if( clientSocket != null) clientSocket.close();
  52. }
  53. catch( IOException ioE) {}
  54. } // end of finally
  55. } // while forever waiting for a client connection
  56. } // main
  57. } // class DateServer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement