26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1028 Networking Chapter 17<br />

39 new ReceivingThread( this, clientSocket ).start();<br />

40<br />

41 // print connection information<br />

42 System.out.println( "Connection received from: " +<br />

43 clientSocket.getInetAddress() );<br />

44<br />

45 } // end while<br />

46<br />

47 } // end try<br />

48<br />

49 // handle exception creating server and connecting clients<br />

50 catch ( IOException ioException ) {<br />

51 ioException.printStackTrace();<br />

52 }<br />

53<br />

54 } // end method startServer<br />

55<br />

56 // when new message is received, broadcast message <strong>to</strong> clients<br />

57 public void messageReceived( String from, String message )<br />

58 {<br />

59 // create String containing entire message<br />

60 String completeMessage = from + MESSAGE_SEPARATOR + message;<br />

61<br />

62 // create and start MulticastSendingThread <strong>to</strong> broadcast<br />

63 // new messages <strong>to</strong> all clients<br />

64 new MulticastSendingThread(<br />

65 completeMessage.getBytes() ).start();<br />

66 }<br />

67<br />

68 // start the server<br />

69 public static void main ( String args[] )<br />

70 {<br />

71 new DeitelMessengerServer().startServer();<br />

72 }<br />

73 }<br />

Server listening on port 5000 ...<br />

Connection received from: SEANSANTRY/XXX.XXX.XXX.XXX<br />

Connection received from: PJD/XXX.XXX.XXX.XXX<br />

Fig. Fig. 17.11 17.11 DeitelMessengerServer application for managing a chat room<br />

(part 2 of 2).<br />

Lines 32–45 listen continuously for new client connections. Line 35 invokes method<br />

accept of class ServerSocket <strong>to</strong> wait for and accept a new client connection. Line 39<br />

creates and starts a new ReceivingThread for the client. Class ReceivingThread<br />

(Fig. 17.14) is a Thread subclass that listens for new incoming messages from a particular<br />

client. The first argument <strong>to</strong> the ReceivingThread construc<strong>to</strong>r is a Message-<br />

Listener (Fig. 17.13), <strong>to</strong> which messages from the client should be delivered. Class<br />

DeitelMessengerServer implements interface MessageListener (line 15) and<br />

therefore can pass the this reference <strong>to</strong> the ReceivingThread construc<strong>to</strong>r.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!