chapter 16 networking

22
Chapter 16 Networking Client/Server Communications Client/Server Communications Simple Client/Server Applications Simple Client/Server Applications Serve Multiple Clients Serve Multiple Clients Create Applet Clients Create Applet Clients Send and Retrieve Ob Send and Retrieve Ob j j ects on the ects on the Network Network The URL Class The URL Class Retrieve Files from the Network Retrieve Files from the Network Retrieve Files from Web Servers Retrieve Files from Web Servers View HTML Pages View HTML Pages

Upload: joben

Post on 21-Jan-2016

49 views

Category:

Documents


0 download

DESCRIPTION

Chapter 16 Networking. Client/Server Communications Simple Client/Server Applications Serve Multiple Clients Create Applet Clients Send and Retrieve Ob j ects on the Network The URL Class Retrieve Files from the Network Retrieve Files from Web Servers View HTML Pages. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 16 Networking

Chapter 16 Networking Client/Server CommunicationsClient/Server Communications Simple Client/Server ApplicationsSimple Client/Server Applications Serve Multiple ClientsServe Multiple Clients Create Applet Clients Create Applet Clients Send and Retrieve ObSend and Retrieve Objjects on the Networkects on the Network The URL ClassThe URL Class Retrieve Files from the NetworkRetrieve Files from the Network Retrieve Files from Web ServersRetrieve Files from Web Servers View HTML PagesView HTML Pages

Page 2: Chapter 16 Networking

Client/Server Communications

Server Host

Server socket on port 8000 SeverSocket server = new ServerSocket(8000);

A client socket Socket socket = server.accept()

Client

Client socket Socket socket = new Socket(host, serverPort#)

I/O Stream

Page 3: Chapter 16 Networking

Coding Client and Server

Page 4: Chapter 16 Networking

Example 16.1 A Client/Server Example

Objective: Write a client to send data to a Objective: Write a client to send data to a server. The server receives the data, uses it server. The server receives the data, uses it to produce a result, and then sends the result to produce a result, and then sends the result back to the client. The client displays the back to the client. The client displays the result on the console. In this example, the result on the console. In this example, the data sent from the client is the radius of a data sent from the client is the radius of a circle, and the result produced bycircle, and the result produced bythe server is the area of the circle. the server is the area of the circle.

Page 5: Chapter 16 Networking

Example 16.1, cont.

Server CodeServer Code RunRun

Client CodeClient Code

Note: Run Server first, then Client. Press Ctrl+C to close the window.

RunRun

Page 6: Chapter 16 Networking

Example 16.2 Serving Multiple Clients

Server for Multiple ClientsServer for Multiple Clients Run ServerRun Server

Note: Run Server first, then Client. Press Ctrl+C to close the window.

Run ClientRun Client

Server

Client n. . .Client 1

A serve socketon a port

A socket for aclient

A socket for aclient

Page 7: Chapter 16 Networking

Applet Clients

Due to security constraints, applets can only Due to security constraints, applets can only connect to the host from which they were loaded. connect to the host from which they were loaded. Therefore, the HTML file must be located on the Therefore, the HTML file must be located on the machine on which the server is running. machine on which the server is running.

Page 8: Chapter 16 Networking

Example 16.3 Creating Applet ClientsObjective: shows how to use an applet to Objective: shows how to use an applet to register students. The client collects and register students. The client collects and sends registration information to the server. sends registration information to the server. The server appends the information to a data The server appends the information to a data file using a random access file stream.file using a random access file stream.

RunRun

Click Run. Type java RegistrationServer and press Enter. Alt+Tab back to this window and click Run again. Type appletviewer registrationClient.html in the second DOS window. Display the Applet Viewer on top of the server window, and enter student information. To end the server session, press Ctrl+C. (Note: This program cannot be run from the CD.)

Client CodeClient CodeServer CodeServer Code

Page 9: Chapter 16 Networking

Example 16.4 Passing Objects in Network ProgramsObjective: This example rewrites Example Objective: This example rewrites Example 16.5, using object streams on the socket. 16.5, using object streams on the socket. Instead of passing name, street, state, and Instead of passing name, street, state, and zips separately, this program passes the zips separately, this program passes the student object as a whole object.student object as a whole object.

Client CodeClient CodeServer CodeServer Code RunRun

Click Run. Type java RegistrationServerUsingObjectStream and press Enter. Alt+Tab back to this window and click Run again. Type java RegistrationClientUsingObjectStream.html in the second DOS window. Display the Applet Viewer on top of the server window, and enter student information. To end the server session, press Ctrl+C. (Note: This program cannot be run from the CD.)

Page 10: Chapter 16 Networking

Viewing HTML Pages Given the URL of the page, a Web browser can Given the URL of the page, a Web browser can

view an HTML page—for example, view an HTML page—for example, http://www.sun.comhttp://www.sun.com. .

HTTP (Hypertext Transfer Protocol) is the common HTTP (Hypertext Transfer Protocol) is the common standard used for communication between a Webstandard used for communication between a Webserver and the Internet. You can open a URL andserver and the Internet. You can open a URL andview a Web page in a Java applet. view a Web page in a Java applet.

A URL is a description of a resourceA URL is a description of a resourcelocation on the Internet. Java provides alocation on the Internet. Java provides aclass—class—java.net.URLjava.net.URL——to manipulateto manipulateURLs.URLs.

Page 11: Chapter 16 Networking

Viewing HTML Pages URL Examples:URL Examples:

http://www.ncsa.uiuc.edu:8080/http://www.ncsa.uiuc.edu:8080/demoweb/url-primer.htmldemoweb/url-primer.html

http://www.ncsa.uiuc.edu/demoweb/url-http://www.ncsa.uiuc.edu/demoweb/url-primer.htmlprimer.html

http://java.sun.com/index.html#chapter1http://java.sun.com/index.html#chapter1 http://java.sun.com/index.htmlhttp://java.sun.com/index.html http://java.sun.com/http://java.sun.com/

Page 12: Chapter 16 Networking

URL public URL(String protocol, String host, int port, String file) throws public URL(String protocol, String host, int port, String file) throws

MalformedURLExceptionMalformedURLException public URL(String protocol, String host,public URL(String protocol, String host, String file) throws MalformedURLExceptionString file) throws MalformedURLException public URL(String url) throws MalformedURLExceptionpublic URL(String url) throws MalformedURLException public String getProtocol()public String getProtocol() public String getHost()public String getHost() public int getPort()public int getPort() public String getFile()public String getFile() public String getRef()public String getRef() public final InputStream openStream()public final InputStream openStream() protected void set(String protocol, String host, int port,protected void set(String protocol, String host, int port, String file, String ref)String file, String ref)

Page 13: Chapter 16 Networking

Creating a URL Instance

The following statement creates a Java URL The following statement creates a Java URL object:object:

try {try {URL location = new URL("http://www.sun.com");URL location = new URL("http://www.sun.com");

} catch(MalformedURLException e) {} catch(MalformedURLException e) {}} ViewingWebPagesViewingWebPages

If necessary, click the Run button to access the DOS prompt. Using a JDK 1.2-enabled Web browser. This applet cannot run using the Applet Viewer utility.

RunRun

Page 14: Chapter 16 Networking

Retrieving Filesfrom Web Servers

The following figure shows the process by which an applet reads the files on the Web server:

Page 15: Chapter 16 Networking

Example 16.6 Retrieving Remote Data Files

Objective: Compute and display student exam Objective: Compute and display student exam scores. The example is similar to Example 15.5. scores. The example is similar to Example 15.5. Rather than reading the file from the local system, Rather than reading the file from the local system, this example reads the file from a Web server. this example reads the file from a Web server.

RetrievingRemoteFileRetrievingRemoteFile

If necessary, click the Run button to access the DOS prompt. Using a Web browser (such as the HotJavaBrowser), enter the following URL:

http://www.geocities.com/liangjava/RetrievingRemoteFile.html

RunRun

Page 16: Chapter 16 Networking

The Web Server You need to place three files on the Web server: You need to place three files on the Web server:

RetrievingRemoteFile.classRetrievingRemoteFile.class RetrievingRemoteFile.htmlRetrievingRemoteFile.html in.dat in.dat

For convenience, place them in one directory.For convenience, place them in one directory.

Page 17: Chapter 16 Networking

Viewing HTML Files Using the JEditorPane

JEditorPane can be used to display HTML files.

WebBrowseWebBrowse

Run Applet ViewerRun Applet Viewer

Page 18: Chapter 16 Networking

JEditorPane

public JEditorPane() create create a new JEditorPane. The document model is set to null

public JEditorPane(String initialPage) throws IOException public JEditorPane(URL initialPage) throws IOException public void addHyperlinkListener(HyperlinkListener listener)

Page 19: Chapter 16 Networking

JEditorPane

public void setPage(URL url) throws IOException public void setPage(String url) throws IOException public URL getPage()

Page 20: Chapter 16 Networking

Distributed TicTacToe Game

Server

Player 2

Session N...

Player 1

Session 1

Player 2Player 1...

Page 21: Chapter 16 Networking

Distributed TicTacToe Game

Server Create a server socket. Accept connection from the first player and notify the player is Player 1 with token X. Accept connection from the second player and notify the player is Player 2 with token O. Start a thread for the session.

Player 1 1. Initialize user interface. 2. Request connection to the server and know which token to use from the server. 3. Get the start signal from the server. 4. Wait for the player to mark a cell, send the cell's row and column index to the server. 5. Receive status from the server. 6. If WIN, display the winner; if player 2 wins, receive the last move from player 2. Break the loop 7. If DRAW, display game is over; break the loop. 8. If CONTINUE, receive player 2's selected row and column index and mark the cell for player 2.

Player 2 1. Initialize user interface. 2. Request connection to the server and know which token to use from the server. 3. Receive status from the server. 4. If WIN, display the winner. If player 1 wins, receive player 1's last move, and break the loop. 5. If DRAW, display game is over, and receive player 1's last move, and break the loop. 6. If CONTINUE, receive player 1's selected row and index and mark the cell for player 1. 7. Wait for the player to move, and send the selected row and column to the server.

Handle a session: 1. Tell player 1 to start. 2. Receive row and column of the selected cell from Player 1. 3. Determine the game status (WIN, DRAW, CONTINUE). If player 1 wins, or drawn, send the status (PLAYER1_WON, DRAW) to both players and send player 1's move to player 2. Exit. . 4. If CONTINUE, notify player 2 to take the turn, and send player 1's newly selected row and column index to player 2. 5. Receive row and column of the selected cell from player 2. 6. If player 2 wins, send the status (PLAYER2_WON) to both players, and send player 2's move to player 1. Exit. 7. If CONTINUE, send the status, and send player 2's newly selected row and column index to Player 1.

Page 22: Chapter 16 Networking

Distributed TicTacToe Game

1. cd c:\department\courses\javaprog\book\2. Start sever: start java TicTacToeServer3. Start 4 clients:

• Start appletviewer TicTacToeClient.html