Download presentation
Presentation is loading. Please wait.
Published byMaud Jones Modified over 9 years ago
1
2005 Pearson Education, Inc. All rights reserved. 1 24 Networking
2
2005 Pearson Education Inc. All rights reserved. 2 If the presence of electricity can be made visible in any part of a circuit, I see no reason why intelligence may not be transmitted instantaneously by electricity. — Samuel F. B. Morse Protocol is everything. — Francois Giuliani What networks of railroads, highways and canals were in another age, the networks of telecommunications, information and computerization … are today. — Bruno Kreisky The port is near, the bells I hear, the people all exulting. — Walt Whitman
3
2005 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn: To understand Java networking with URLs, sockets and datagrams. To implement Java networking applications by using sockets and datagrams. To understand how to implement Java clients and servers that communicate with one another. To understand how to implement network-based collaborative applications. To construct a multithreaded server.
4
2005 Pearson Education, Inc. All rights reserved. 4 24.1 Introduction 24.2 Manipulating URLs 24.3 Reading a File on a Web Server 24.4 Establishing a Simple Server Using Stream Sockets 24.5 Establishing a Simple Client Using Stream Sockets 24.6 Client/Server Interaction with Stream Socket Connections 24.7 Connectionless Client/Server Interaction with Datagrams 24.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server 24.9 Security and the Network 24.10 Case Study: DeitelMessenger Server and Client 24.10.1 DeitelMessengerServer and Supporting Classes 24.10.2 DeitelMessenger Client and Supporting Classes 24.11 Wrap-Up
5
2005 Pearson Education, Inc. All rights reserved. 5 24.1 Introduction Networking package is java.net – Stream-based communications Applications view networking as streams of data Connection-based protocol Uses TCP (Transmission Control Protocol – Packet-based communications Individual packets transmitted Connectionless service Uses UDP (User Datagram Protocol)
6
2005 Pearson Education, Inc. All rights reserved. 6 24.1 Introduction (Cont.) Client-server relationship – Client requests some action be performed – Server performs the action and responds to client – Request-response model Common implementation: Web browsers and Web servers
7
2005 Pearson Education, Inc. All rights reserved. 7 Performance Tip 24.1 Connectionless services generally offer greater performance but less reliability than connection- oriented services.
8
2005 Pearson Education, Inc. All rights reserved. 8 TCP, UDP and related protocols enable a great variety of heterogeneous computer systems (i.e., computer systems with different processors and different operating systems) to intercommunicate. Portability Tip 24.1
9
2005 Pearson Education, Inc. All rights reserved. 9 24.2 Manipulating URLs HyperText Transfer Protocol (HTTP) – Uses URIs (Uniform Resource Identifiers) to identify data URLs (Uniform Resource Locators) – URIs that specify the locations of documents – Refer to files, directories and complex objects HTML document SiteSelector.html (Fig. 24.1) – applet element – param tag name attribute value attribute
10
2005 Pearson Education, Inc. All rights reserved. 10 Outline Fig.24.17 | HTML document to load SiteSelector applet. Declare param tags for the applet, each parameter has a name and a value SiteSelector.html Lines 5-12
11
2005 Pearson Education, Inc. All rights reserved. 11 Outline SiteSelector.java (1 of 5) Lines 3-4 Line 8 Import classes in package java.net Import interface AppletContext from package java.net
12
2005 Pearson Education, Inc. All rights reserved. 12 Outline SiteSelector.java (2 of 5) Lines 39-52 Line 45 Line 48 Line 51 When the user selects one of the Web sites listed in siteChooser, the program calls method valueChanged Pass the selected site name (the key) to HashMap method get, which locates and returns a reference to the corresponding URL (the value) Get a reference to an AppletContext object that represents the applet container Display in the current browser window the resource associated with URL newDocument
13
2005 Pearson Education, Inc. All rights reserved. 13 Outline SiteSelector.java (3 of 5) Line 67 Line 73 Line 77 Lines 81-84 Use Applet method getParameter to obtain a Web site title Use Applet method getParameter to obtain the Web site location Use the location as the value of a new URL object If the location passed to the URL constructor is invalid, the URL constructor throws a MalformedURLException
14
2005 Pearson Education, Inc. All rights reserved. 14 Outline SiteSelector.java (4 of 5) Line 87 Program output Use Applet method getParameter to obtain the next site title
15
2005 Pearson Education, Inc. All rights reserved. 15 Outline SiteSelector.java (5 of 5) Program output
16
2005 Pearson Education, Inc. All rights reserved. 16 24.2 Manipulating URLs HTML frames – Specify target frame in method showDocument _blank _self _top
17
2005 Pearson Education, Inc. All rights reserved. 17 Error-Prevention Tip 24.1 The applet in Fig. 24.2 must be run from a Web browser, such as Mozilla or Microsoft Internet Explorer, to see the results of displaying another Web page. The appletviewer is capable only of executing applets—it ignores all other HTML tags. If the Web sites in the program contained Java applets, only those applets would appear in the appletviewer when the user selected a Web site. Each applet would execute in a separate appletviewer window.
18
2005 Pearson Education, Inc. All rights reserved. 18 24.3 Reading a File on a Web Server Swing GUI component JEditorPane – Render both plain text and HTML-formatted text – Act as a simple Web browser Retrieves files from a Web server at a given URI HyperlinkEvent s – Occur when the user clicks a hyperlink – Three event types HyperlinkEvent.EventType.ACTIVATED HyperlinkEvent.EventType.ENTERED HyperlinkEvent.EventType.EXITED
19
2005 Pearson Education, Inc. All rights reserved. 19 Outline ReadServerFile.java (1 of 3) Lines 7, 12 and 13 Line 18 Import JEditPane from package javax.swing, import HyperlinkEvent and HyperlinkListener from package javax.swing.event Declare JEditorPane contentsArea, which will be used to display the contents of the file
20
2005 Pearson Education, Inc. All rights reserved. 20 Outline ReadServerFile.java (2 of 3) Line 40 Line 41 Lines 42-53 Lines 46-51 Lines 48-49 Line 50 Create JEditorPane using the no-argument constructor Set JEditorPane editable property to false Register a HyperlinkListener to handle HyperlinkEvents, which occur when the user clicks a hyperlink in the JEditorPane Method hyperlinkUpdate is called when a HyperlinkEvent occurs Use HyperlinkEvent method getEventType to determine the type of the HyperlinkEvent Use HyperlinkEvent method getURL to obtain the URL represented by the hyperlink
21
2005 Pearson Education, Inc. All rights reserved. 21 Outline ReadServerFile.java (3 of 3) Line 65 Invoke JEditorPane method setPage to download the document specified by location and display it in the JEditPane
22
2005 Pearson Education, Inc. All rights reserved. 22 Outline ReadServerFileTest.java (1 of 2) Program output
23
2005 Pearson Education, Inc. All rights reserved. 23 Outline ReadServerFileTest.java (2 of 2) Program output
24
2005 Pearson Education, Inc. All rights reserved. 24 A JEditorPane generates HyperlinkEvents only if it is uneditable. Look-and-Feel Observation 24.1
25
2005 Pearson Education, Inc. All rights reserved. 25 24.4 Establishing a Simple Server Using Stream Sockets Five steps to create a simple server in Java – Step 1: Create ServerSocket object ServerSocket server = new ServerSocket( portNumber, queueLength ); Register an available port Specify a maximum number of clients Handshake point Binding the server to the port – Only one client can be bound to a specific port
26
2005 Pearson Education, Inc. All rights reserved. 26 Software Engineering Observation 24.1 Port numbers can be between 0 and 65,535. Most operating systems reserve port numbers below 1024 for system services (e.g., e-mail and World Wide Web servers). Generally, these ports should not be specified as connection ports in user programs. In fact, some operating systems require special access privileges to bind to port numbers below 1024.
27
2005 Pearson Education, Inc. All rights reserved. 27 24.4 Establishing a Simple Server Using Stream Sockets (Cont.) Five steps to create a simple server in Java – Step 2: Server listens for client connection Server blocks until client connects Socket connection = server.accept(); – Step 3: Sending and receiving data OutputStream to send and InputStream to receive data – Method getOutputStream returns Socket ’s OutputStream – Methods getInputstream returns Socket ’s InputStream
28
2005 Pearson Education, Inc. All rights reserved. 28 24.4 Establishing a Simple Server Using Stream Sockets (Cont.) Five steps to create a simple server in Java – Step 4: Process phase Server and Client communicate via streams – Step 5: Close streams and connections Method close
29
2005 Pearson Education, Inc. All rights reserved. 29 With sockets, network I/O appears to Java programs to be similar to sequential file I/O. Sockets hide much of the complexity of network programming from the programmer. Software Engineering Observation 24.2
30
2005 Pearson Education, Inc. All rights reserved. 30 With Java’s multithreading, we can create multithreaded servers that can manage many simultaneous connections with many clients. This multithreaded-server architecture is precisely what popular network servers use. Software Engineering Observation 24.3
31
2005 Pearson Education, Inc. All rights reserved. 31 A multithreaded server can take the Socket returned by each call to accept and create a new thread that manages network I/O across that Socket. Alternatively, a multithreaded server can maintain a pool of threads (a set of already existing threads) ready to manage network I/O across the new Sockets as they are created. See Chapter 23 for more information on multithreading. Software Engineering Observation 24.4
32
2005 Pearson Education, Inc. All rights reserved. 32 Performance Tip 24.2 In high-performance systems in which memory is abundant, a multithreaded server can be implemented to create a pool of threads that can be assigned quickly to handle network I/O across each new Socket as it is created. Thus, when the server receives a connection, it need not incur the overhead of thread creation. When the connection is closed, the thread is returned to the pool for reuse.
33
2005 Pearson Education, Inc. All rights reserved. 33 24.5 Establishing a Simple Client Using Stream Sockets Four steps to create a simple client in Java – Step 1: Create a Socket to connect to server Socket connection = new Socket ( serverAddress, port ); – Step 2: Obtain Socket ’s InputStream and Outputstream – Step 3: Process information communicated – Step 4: Close streams and connection
34
2005 Pearson Education, Inc. All rights reserved. 34 24.6 Client/Server Interaction with Stream Socket Connections Client/server chat application – Uses stream sockets – Server waits for a client connection attempt – Client connects to the server Send and receive messages – Client or server terminates the connection – Server waits for the next client to connect
35
2005 Pearson Education, Inc. All rights reserved. 35 Outline Server.java (1 of 8) Lines 8-9 Line 25 Line 26 Import ServerSocket and Socket from package java.net Declare ServerSocket server which waits for client connection Declare Socket connection which connects to the client
36
2005 Pearson Education, Inc. All rights reserved. 36 Outline Server.java (2 of 8)
37
2005 Pearson Education, Inc. All rights reserved. 37 Outline Server.java (3 of 8) Line 62 Line 68 Line 69 Line 70 Create ServerSocket at port 12345 with queue of length 100 Wait for a client connection After the connection is established, obtain references to the streams for the connection Send the initial connection message to the client and process all messages received from the client
38
2005 Pearson Education, Inc. All rights reserved. 38 Outline Server.java (4 of 8) Line 93 Line 95 Line 102 Line 103 Use ServerSocket method accept to wait for a connection from a client Output the host name of the computer that made the connection using Socket method getInetAddress and InetAddress method getHostName Obtain Socket ’s OutputStream and use it to initialize ObjectOutputStream Method flush empties output buffer and sends header information
39
2005 Pearson Education, Inc. All rights reserved. 39 Outline Server.java (5 of 8) Line 106 Line 124 Obtain Socket ’s InputStream and use it to initialize ObjectInputStream Use ObjectInputStream method readObject to read a String from client
40
2005 Pearson Education, Inc. All rights reserved. 40 Outline Server.java (6 of 8) Lines 136-151 Line 145 Line 158 Method closeConnection closes streams and sockets Invoke Socket method close to close the socket Use ObjectOutputStream method writeObject to send a String to client
41
2005 Pearson Education, Inc. All rights reserved. 41 Outline Server.java (7 of 8)
42
2005 Pearson Education, Inc. All rights reserved. 42 Outline Server.java (8 of 8)
43
2005 Pearson Education, Inc. All rights reserved. 43 Outline ServerTest.java
44
2005 Pearson Education, Inc. All rights reserved. 44 Common Programming Error 24.1 Specifying a port that is already in use or specifying an invalid port number when creating a ServerSocket results in a BindException.
45
2005 Pearson Education, Inc. All rights reserved. 45 Software Engineering Observation 24.5 When using an ObjectOutputStream and ObjectInputStream to send and receive data over a network connection, always create the ObjectOutputStream first and flush the stream so that the client’s ObjectInputStream can prepare to receive the data. This is required only for networking applications that communicate using ObjectOutputStream and ObjectInputStream.
46
2005 Pearson Education, Inc. All rights reserved. 46 Performance Tip 24.3 A computer’s input and output components are typically much slower than its memory. Output buffers typically are used to increase the efficiency of an application by sending larger amounts of data fewer times, thus reducing the number of times an application accesses the computer’s input and output components.
47
2005 Pearson Education, Inc. All rights reserved. 47 Outline Client.java (1 of 7)
48
2005 Pearson Education, Inc. All rights reserved. 48 Outline Client.java (2 of 7)
49
2005 Pearson Education, Inc. All rights reserved. 49 Outline Client.java (3 of 7)
50
2005 Pearson Education, Inc. All rights reserved. 50 Outline Client.java (4 of 7) Line 87 Lines 90-91 Line 98 Line 99 Create a Socket that will connect with port 12345 on the server Use InetAddress static method getByName to obtain an InetAdress object containing the IP address specified as a command- line argument to the application Display a message indicating the name of the server computer to which the client has connected Method flush empties output buffer and sends header information Obtain Socket ’s OutputStream and use it to initialize ObjectOutputStream
51
2005 Pearson Education, Inc. All rights reserved. 51 Outline Client.java (5 of 7) Line 117 Line 138 Read a String object from server Invoke Socket method close to close the socket
52
2005 Pearson Education, Inc. All rights reserved. 52 Outline Client.java (6 of 7) Line 151 Use ObjectOutputStream method writeObject to send a String to server
53
2005 Pearson Education, Inc. All rights reserved. 53 Outline Client.java (7 of 7)
54
2005 Pearson Education, Inc. All rights reserved. 54 Outline ClientTest.java (1 of 2) Program output
55
2005 Pearson Education, Inc. All rights reserved. 55 Outline ClientTest.java (2 of 2) Program output
56
2005 Pearson Education, Inc. All rights reserved. 56 24.7 Connectionless Client/Server Interaction with Datagrams Connectionless transmission with datagrams – No connection maintained with other computer – Break message into separate pieces and send as packets – Message arrive in order, out of order or not at all – Receiver puts messages in order and reads them
57
2005 Pearson Education, Inc. All rights reserved. 57 Outline Server.java (1 of 4) Line 16 Use a DatagramSocket as our server
58
2005 Pearson Education, Inc. All rights reserved. 58 Outline Server.java (2 of 4) Line 30 Lines 47-48 Line 50 Use the DatagramSocket constructor that takes an integer port number argument to bind the server to a port where it can receive packets from clients Create a DatagramPacket in which a received packet of information can be stored Use DatagramSocket method receive to wait for a packet to arrive at the server
59
2005 Pearson Education, Inc. All rights reserved. 59 Outline Server.java (3 of 4) Line 54 Line 55 Line 56 Line 57 Lines 77-79 Use DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sent Use DatagramPacket method getPort to obtain the port number through which the host computer sent the packet Use DatagramPacket method getLength to obtain the number of bytes of data sent Use DatagramPacket method getData to obtain an byte array containing the data Create a DatagramPacket, which specifies the data to send, the number of bytes to send, the client computer’s Internet address and the port where the client is waiting to receive packets
60
2005 Pearson Education, Inc. All rights reserved. 60 Outline Server.java (4 of 4) Use method send of DatagramSocket to send the packet over the network
61
2005 Pearson Education, Inc. All rights reserved. 61 Outline ServerTest.java Program ouptut Server window after packet of data is received from client
62
2005 Pearson Education, Inc. All rights reserved. 62 Outline Client.java (1 of 5)
63
2005 Pearson Education, Inc. All rights reserved. 63 Outline Client.java (2 of 5) Line 41 Lines 44-45 Line 47 Convert the String to a byte array Create a DatagramPacket and initialize it with the byte array, the length of the string that was entered by the user, the IP address to which the packet is to be sent and the port number at which the server is waiting Use DatagramPacket method send to send the packet
64
2005 Pearson Education, Inc. All rights reserved. 64 Outline Client.java (3 of 5) Line 71 Create a DatagramSocket for sending and receiving packets
65
2005 Pearson Education, Inc. All rights reserved. 65 Outline Client.java (4 of 5) Lines 88-89 Line 95 Line 96 Line 97 Line 98 Create a DatagramPacket to store received information Use DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sent Use DatagramPacket method getPort to obtain the port number through which the host computer sent the packet Use DatagramPacket method getLength to obtain the number of bytes of data sent Use DatagramPacket method getData to obtain an byte array containing the data
66
2005 Pearson Education, Inc. All rights reserved. 66 Outline Client.java (5 of 5)
67
2005 Pearson Education, Inc. All rights reserved. 67 Outline ClientTest.java Program output Client window after sending packet to Server and receiving packet back from Server
68
2005 Pearson Education, Inc. All rights reserved. 68 Common Programming Error 24.2 Specifying a port that is already in use or specifying an invalid port number when creating a DatagramSocket results in a SocketException.
69
2005 Pearson Education, Inc. All rights reserved. 69 24.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server Multiple threads – Server uses one thread per player Allow each player to play game independently
70
2005 Pearson Education, Inc. All rights reserved. 70 Outline TicTacToeServer.java (1 of 12)
71
2005 Pearson Education, Inc. All rights reserved. 71 Outline TicTacToeServer.java (2 of 12)
72
2005 Pearson Education, Inc. All rights reserved. 72 Outline TicTacToeServer.java (3 of 12) Line 50 Line 55 Create array players with 2 elements Create ServerSocket to listen on port 12345
73
2005 Pearson Education, Inc. All rights reserved. 73 Outline TicTacToeServer.java (4 of 12) Lines 75-87 Line 79 Line 80 Loop twice, blocking at line 79 each time while waiting for a client connection Create a new Player object to manage the connection as a separate thread Execute the Player in the runGame thread pool
74
2005 Pearson Education, Inc. All rights reserved. 74 Outline TicTacToeServer.java (5 of 12)
75
2005 Pearson Education, Inc. All rights reserved. 75 Outline TicTacToeServer.java (6 of 12)
76
2005 Pearson Education, Inc. All rights reserved. 76 Outline TicTacToeServer.java (7 of 12)
77
2005 Pearson Education, Inc. All rights reserved. 77 Outline TicTacToeServer.java (8 of 12) Lines 200-201 Get the streams to send and receive data
78
2005 Pearson Education, Inc. All rights reserved. 78 Outline TicTacToeServer.java (9 of 12) Lines 213-214 Line 215 Lines 225-226 Format output notifying the other player of the move Call Formatter method flush to force the output to the client Send player’s mark
79
2005 Pearson Education, Inc. All rights reserved. 79 Outline TicTacToeServer.java (10 of 12) Lines 231-233 Lines 254-255 Send message indicating one player connected and waiting for another player to arrive Begin the game
80
2005 Pearson Education, Inc. All rights reserved. 80 Outline TicTacToeServer.java (11 of 12) Lines 259-260 Line 269 Lines 272 Lines 275-276 Send message indicating player O connected Read a moveCheck the moveSend message indicating the move is valid
81
2005 Pearson Education, Inc. All rights reserved. 81 Outline TicTacToeServer.java (12 of 12) Lines 280-281 Send message indicating the move is invalid
82
2005 Pearson Education, Inc. All rights reserved. 82 Outline TicTacToeServer Test.java Program output
83
2005 Pearson Education, Inc. All rights reserved. 83 Outline TicTacToeClient.java (1 of 10)
84
2005 Pearson Education, Inc. All rights reserved. 84 Outline TicTacToeClient.java (2 of 10)
85
2005 Pearson Education, Inc. All rights reserved. 85 Outline TicTacToeClient.java (3 of 10)
86
2005 Pearson Education, Inc. All rights reserved. 86 Outline TicTacToeClient.java (4 of 10) Lines 85-86 Lines 89-90 Line 105 Connect to the serverGet the streams to send and receive data Read mark character from server
87
2005 Pearson Education, Inc. All rights reserved. 87 Outline TicTacToeClient.java (5 of 10) Lines 121-125 Lines 123-124 Lines 132-136 Loop continually Read and process messages from server If valid move, write message and set mark in square
88
2005 Pearson Education, Inc. All rights reserved. 88 Outline TicTacToeClient.java (6 of 10) Lines 137-141 Lines 142-153 If invalid move, display message If opponent moves, set mark in square
89
2005 Pearson Education, Inc. All rights reserved. 89 Outline TicTacToeClient.java (7 of 10)
90
2005 Pearson Education, Inc. All rights reserved. 90 Outline TicTacToeClient.java (8 of 10) Lines 192-193 Send the move to the server
91
2005 Pearson Education, Inc. All rights reserved. 91 Outline TicTacToeClient.java (9 of 10)
92
2005 Pearson Education, Inc. All rights reserved. 92 Outline TicTacToeClient.java (10 of 10)
93
2005 Pearson Education, Inc. All rights reserved. 93 Outline TicTacToeClient Test.java
94
2005 Pearson Education, Inc. All rights reserved. 94 Fig.24.17 | Sample outputs from the client/server Tic-Tac-Toe program. (Part 1 of 2.)
95
2005 Pearson Education, Inc. All rights reserved. 95 Fig.24.17 | Sample outputs from the client/server Tic-Tac-Toe program. (Part 2 of 2.)
96
2005 Pearson Education, Inc. All rights reserved. 96 24.9 Security and the Network By default, applets cannot perform file processing Applets often limited in machine access – Applets can communicate only with the machine from which it was originally downloaded Java Security API – Digitally signed applets – Applets given more privileges if from trusted source
97
2005 Pearson Education, Inc. All rights reserved. 97 24.10 Case Study: DeitelMessenger Server and Client Chat rooms – Each user can post a message and read all other messages – Multicast Send packets to groups of clients
98
2005 Pearson Education, Inc. All rights reserved. 98 24.10.1 DeitelMessengerServer and Supporting Classes DeitelMessengerServer – Online chat system – Classes: DeitelMessengerServer – Clients connect to this server Interface SocketMessengerConstants – Defines constants for port numbers Interface MessageListener – Defines method for receiving new chat messages Class MessageReceiver – Separate thread listens for messages from clients Class MulticastSender – Separate thread delivers outgoing messages to clients
99
2005 Pearson Education, Inc. All rights reserved. 99 Outline DeiterMessenger Server.java (1 of 3) Line 15 Lines 28-29 Implement the MessageListener interface Create a ServerSocket to accept incoming network connections
100
2005 Pearson Education, Inc. All rights reserved. 100 Outline DeiterMessenger Server.java (2 of 3) Line 38 Lines 41-42 Invoke method accept to wait for and accept a new client connection Create and start a new MessageReceiver for the client
101
2005 Pearson Education, Inc. All rights reserved. 101 Outline DeiterMessenger Server.java (3 of 3) Lines 62-63 Create and start new MulticastSender to deliver completeMessage to all clients
102
2005 Pearson Education, Inc. All rights reserved. 102 Outline DeitelMessenger ServerTest.java Program output
103
2005 Pearson Education, Inc. All rights reserved. 103 Outline SocketMessenger Constants.java Line 9 Line 12 Line 15 Line 18 Line 21 Line 24 Line 27 Address to send multicast datagrams Port listening for multicast datagrams Port for sending multicast datagrams Port for socket connections to server String that indicates disconnect String that separates user name and message Maximum message size in bytes
104
2005 Pearson Education, Inc. All rights reserved. 104 Outline MessageListener.java Line 9 Method messageReceived allows an implementing class to receive chat messages
105
2005 Pearson Education, Inc. All rights reserved. 105 Outline MessageReceiver.java (1 of 5)
106
2005 Pearson Education, Inc. All rights reserved. 106 Outline MessageReceiver.java (2 of 5) Line 31 Attempt to read for five seconds
107
2005 Pearson Education, Inc. All rights reserved. 107 Outline MessageReceiver.java (3 of 5) Line 53 Line 55 Lines 69-70 Read line of data from client A SocketTimeOutException is thrown if the read times out Separate message into two tokens delimited by Message_SEPARATOR
108
2005 Pearson Education, Inc. All rights reserved. 108 Outline MessageReceiver.java (4 of 5) Lines 77-79 Lines 84-85 Invoke method messageReceived of interface MessageListener to deliver the new message to the registered MessageListener Determine whether message indicates that user wishes to leave chat room
109
2005 Pearson Education, Inc. All rights reserved. 109 Outline MessageReceiver.java (5 of 5)
110
2005 Pearson Education, Inc. All rights reserved. 110 Outline MulticastSender.java (1 of 2) Lines 27-28 Create DatagramSocket for delivering DatagramPacket s via multicast
111
2005 Pearson Education, Inc. All rights reserved. 111 Outline MulticastSender.java (2 of 2) Line 31 Lines 34-35 Line 37 Line 38 Create an InetAddress object for the multicast address Create the Datagrampacket containing the message Send the packet with DatagramSocket method send Close the DatagramSocket, and the run method returns, terminating the MulticastSender
112
2005 Pearson Education, Inc. All rights reserved. 112 24.10.1 DeitelMessengerServer and Supporting Classes Execute DeitelMessengerServerTest – Change directories to the proper location – Type command java com.deitel.mesenger.sockets.server.DeitelMessengerServerTest
113
2005 Pearson Education, Inc. All rights reserved. 113 24.10.2 DeitelMessenger Client and Supporting Classes DeitelMessengerServer client – Consists several components Interface MessageManager Class that implements interface MessageManager – Manages communication with server Runnable subclass – Listens for messages at server’s multicast address Another Runnable subclass – Sends messages from client to server JFrame subclass – Provides client GUI
114
2005 Pearson Education, Inc. All rights reserved. 114 Outline MessageManager.java Line 10 Line 14 Line 17 Connects MessageManager to DeitelMessengerServer and routes incoming messages to appropriate MessageListener Disconnects MessageManager from DeitelMessengerServer and stops delivering messages to MessageListener Sends new message to DeitelMessengerServer
115
2005 Pearson Education, Inc. All rights reserved. 115 Outline SocketMessage Manager.java (1 of 4) Line 20 Line 22 Socket for connecting and sending messages to DeitelMessengerServer Runnable listens for incoming messages
116
2005 Pearson Education, Inc. All rights reserved. 116 Outline SocketMessage Manager.java (2 of 4) Lines 40-41 Line 44 Line 45 Create Socket to communicate with DeitelMessengerServer Create a new packetReceiver, which listens for incoming multicast messages from the server Execute the Runnable
117
2005 Pearson Education, Inc. All rights reserved. 117 Outline SocketMessage Manager.java (3 of 4) Lines 63-64 Line 65 Line 66 Create a new MessageSender to send DISCONNECT_STRING to the server Start the MessageSender to deliver the message using method submit of ExecutorService Invoke Future method get to wait for the disconnect message to be delivered and the Runnable to terminate
118
2005 Pearson Education, Inc. All rights reserved. 118 Outline SocketMessage Manager.java (4 of 4) Lines 93-94 Create and start a new MessageSender to deliver the new message in a separate thread of execution
119
2005 Pearson Education, Inc. All rights reserved. 119 Outline MessageSender.java (1 of 2)
120
2005 Pearson Education, Inc. All rights reserved. 120 Outline MessageSender.java (2 of 2) Lines 29-30 Line 31 Line 32 Create a new Formatter for the clientSocket ’s OutputStream Invoke Formatter method format to format the message Invoke Formatter method flush to ensure that the message is sent immediately
121
2005 Pearson Education, Inc. All rights reserved. 121 Outline PacketReceiver.java (1 of 4)
122
2005 Pearson Education, Inc. All rights reserved. 122 Outline PacketReceiver.java (2 of 4) Lines 30-31 Line 34 Line 37 Line 40 Line 55 MulticastSocket listens for incoming chat messages on port MULTICAST_LISTENING_PORT InetAddress object to which DeitelMessengerServer multicasts chat messages Register MulticastSocket to receive messages sent to MULTICAST_ADDRESS Invoke MulticastSocket method setSoTimeout to specify that if no data is received in 5000 milliseconds, the MulticastSocket should issue an InterruptedIOException Create byte array for storing DatagramPacket
123
2005 Pearson Education, Inc. All rights reserved. 123 Outline PacketReceiver.java (3 of 4) Lines 58-59 Line 63 Line 78 Lines 81-82 Create DatagramPacket for storing message Receive incoming packet from multicast address Invoke method trim of class String to remove extra white spaces from the end of the message Create a StringTokenizer to separate the message body from the name of the user who sent the message
124
2005 Pearson Education, Inc. All rights reserved. 124 Outline PacketReceiver.java (4 of 4) Lines 89-91 Line 97 Line 98 After parsing message, deliver message to PacketReceiver ’s MessageListener Invoke MulicastSocket method leaveGroup to stop receiving messages from the multicast address Invoke MulticastSocket method close to close the MulticastSocket
125
2005 Pearson Education, Inc. All rights reserved. 125 Outline ClientGUI.java (1 of 10)
126
2005 Pearson Education, Inc. All rights reserved. 126 Outline ClientGUI.java (2 of 10) Line 40 Line 41 MessageManager handles communication with chat server MessageListener receives incoming messages from MessageManager
127
2005 Pearson Education, Inc. All rights reserved. 127 Outline ClientGUI.java (3 of 10) Line 51 Create an instance of MyMessageListener, which implements interface MessageListener
128
2005 Pearson Education, Inc. All rights reserved. 128 Outline ClientGUI.java (4 of 10)
129
2005 Pearson Education, Inc. All rights reserved. 129 Outline ClientGUI.java (5 of 10) Lines 128-129 Send user’s name and inputArea ’s text to DeitelMessengerServer as a chat message
130
2005 Pearson Education, Inc. All rights reserved. 130 Outline ClientGUI.java (6 of 10) Line 155 Disconnect from chat server when user exits client application
131
2005 Pearson Education, Inc. All rights reserved. 131 Outline ClientGUI.java (7 of 10) Line 169 Lines 172-173 When user accesses Connect menu, connect to chat server Prompt the user for a user name
132
2005 Pearson Education, Inc. All rights reserved. 132 Outline ClientGUI.java (8 of 10) Line 195 Invoke MessageManager method disconnect to disconnect from chat server
133
2005 Pearson Education, Inc. All rights reserved. 133 Outline ClientGUI.java (9 of 10) Lines 211-216 Display message when MessageListener detects that message was received
134
2005 Pearson Education, Inc. All rights reserved. 134 Outline ClientGUI.java (10 of 10) Line 237 Append the user name, “> ” and messageBody to messageArea
135
2005 Pearson Education, Inc. All rights reserved. 135 Outline DeitelMessenger.java (1 of 3) Line 17 Line 20 Line 23 Create a client to connect to the localhost Connect to a host supplied by the user Create a ClientGUI for the MessageManager
136
2005 Pearson Education, Inc. All rights reserved. 136 Outline DeitelMessenger.java (2 of 3)
137
2005 Pearson Education, Inc. All rights reserved. 137 Outline DeitelMessenger.java (3 of 3)
138
2005 Pearson Education, Inc. All rights reserved. 138 24.10.2 DeitelMessenger Client and Supporting Classes Execute DeitelMessenger client application – Change directories to the proper location – Type command java com.deitel.messenger.sockets.client.DeitelMessenger java com.deitel.messenger.sockets.client.DeitelMessenger localhost java com.deitel.messenger.sockets.client.DeitelMessenger 127.0.0.1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.