PageRenderTime 115ms CodeModel.GetById 20ms RepoModel.GetById 7ms app.codeStats 0ms

/javanotes5.1/source/CLChatServer.java

#
Java | 156 lines | 88 code | 21 blank | 47 comment | 12 complexity | 29510eca576265b86bfc3349ce0267d8 MD5 | raw file
  1. import java.net.*;
  2. import java.io.*;
  3. /**
  4. * This program is one end of a simple command-line interface chat program.
  5. * It acts as a server which waits for a connection from the CLChatClient
  6. * program. The port on which the server listens can be specified as a
  7. * command-line argument. If it is not, then the port specified by the
  8. * constant DEFAULT_PORT is used. Note that if a port number of zero is
  9. * specified, then the server will listen on any available port.
  10. * This program only supports one connection. As soon as a connection is
  11. * opened, the listening socket is closed down. The two ends of the connection
  12. * each send a HANDSHAKE string to the other, so that both ends can verify
  13. * that the program on the other end is of the right type. Then the connected
  14. * programs alternate sending messages to each other. The client always sends
  15. * the first message. The user on either end can close the connection by
  16. * entering the string "quit" when prompted for a message. Note that the first
  17. * character of any string sent over the connection must be 0 or 1; this
  18. * character is interpreted as a command.
  19. */
  20. public class CLChatServer {
  21. /**
  22. * Port to listen on, if none is specified on the command line.
  23. */
  24. static final int DEFAULT_PORT = 1728;
  25. /**
  26. * Handshake string. Each end of the connection sends this string to the
  27. * other just after the connection is opened. This is done to confirm that
  28. * the program on the other side of the connection is a CLChat program.
  29. */
  30. static final String HANDSHAKE = "CLChat";
  31. /**
  32. * This character is prepended to every message that is sent.
  33. */
  34. static final char MESSAGE = '0';
  35. /**
  36. * This character is sent to the connected program when the user quits.
  37. */
  38. static final char CLOSE = '1';
  39. public static void main(String[] args) {
  40. int port; // The port on which the server listens.
  41. ServerSocket listener; // Listens for a connection request.
  42. Socket connection; // For communication with the client.
  43. BufferedReader incoming; // Stream for receiving data from client.
  44. PrintWriter outgoing; // Stream for sending data to client.
  45. String messageOut; // A message to be sent to the client.
  46. String messageIn; // A message received from the client.
  47. BufferedReader userInput; // A wrapper for System.in, for reading
  48. // lines of input from the user.
  49. /* First, get the port number from the command line,
  50. or use the default port if none is specified. */
  51. if (args.length == 0)
  52. port = DEFAULT_PORT;
  53. else {
  54. try {
  55. port= Integer.parseInt(args[0]);
  56. if (port < 0 || port > 65535)
  57. throw new NumberFormatException();
  58. }
  59. catch (NumberFormatException e) {
  60. System.out.println("Illegal port number, " + args[0]);
  61. return;
  62. }
  63. }
  64. /* Wait for a connection request. When it arrives, close
  65. down the listener. Create streams for communication
  66. and exchange the handshake. */
  67. try {
  68. listener = new ServerSocket(port);
  69. System.out.println("Listening on port " + listener.getLocalPort());
  70. connection = listener.accept();
  71. listener.close();
  72. incoming = new BufferedReader(
  73. new InputStreamReader(connection.getInputStream()) );
  74. outgoing = new PrintWriter(connection.getOutputStream());
  75. outgoing.println(HANDSHAKE); // Send handshake to client.
  76. outgoing.flush();
  77. messageIn = incoming.readLine(); // Receive handshake from client.
  78. if (! HANDSHAKE.equals(messageIn) ) {
  79. throw new Exception("Connected program is not a CLChat!");
  80. }
  81. System.out.println("Connected. Waiting for the first message.");
  82. }
  83. catch (Exception e) {
  84. System.out.println("An error occurred while opening connection.");
  85. System.out.println(e.toString());
  86. return;
  87. }
  88. /* Exchange messages with the other end of the connection until one side
  89. or the other closes the connection. This server program waits for
  90. the first message from the client. After that, messages alternate
  91. strictly back and forth. */
  92. try {
  93. userInput = new BufferedReader(new InputStreamReader(System.in));
  94. System.out.println("NOTE: Enter 'quit' to end the program.\n");
  95. while (true) {
  96. System.out.println("WAITING...");
  97. messageIn = incoming.readLine();
  98. if (messageIn.length() > 0) {
  99. // The first character of the message is a command. If
  100. // the command is CLOSE, then the connection is closed.
  101. // Otherwise, remove the command character from the
  102. // message and procede.
  103. if (messageIn.charAt(0) == CLOSE) {
  104. System.out.println("Connection closed at other end.");
  105. connection.close();
  106. break;
  107. }
  108. messageIn = messageIn.substring(1);
  109. }
  110. System.out.println("RECEIVED: " + messageIn);
  111. System.out.print("SEND: ");
  112. messageOut = userInput.readLine();
  113. if (messageOut.equalsIgnoreCase("quit")) {
  114. // User wants to quit. Inform the other side
  115. // of the connection, then close the connection.
  116. outgoing.println(CLOSE);
  117. outgoing.flush(); // Make sure the data is sent!
  118. connection.close();
  119. System.out.println("Connection closed.");
  120. break;
  121. }
  122. outgoing.println(MESSAGE + messageOut);
  123. outgoing.flush(); // Make sure the data is sent!
  124. if (outgoing.checkError()) {
  125. throw new IOException("Error occurred while transmitting message.");
  126. }
  127. }
  128. }
  129. catch (Exception e) {
  130. System.out.println("Sorry, an error has occurred. Connection lost.");
  131. System.out.println("Error: " + e);
  132. System.exit(1);
  133. }
  134. } // end main()
  135. } //end class CLChatServer