Kĩ thuật lập trình - Chương 24: Networking
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
96 trang |
Chia sẻ: huyhoang44 | Lượt xem: 758 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Chương 24: Networking, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
24Networking 1 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. MorseProtocol is everything.Francois GiulianiWhat networks of railroads, highways and canals were in another age, the networks of telecommunications, information and computerization are today.Bruno KreiskyThe port is near, the bells I hear, the people all exulting. Walt Whitman2OBJECTIVESIn 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.3 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 Network24.10 Wrap-Up424.1 IntroductionNetworking package is java.netStream-based communicationsApplications view networking as streams of dataConnection-based protocolUses TCP (Transmission Control ProtocolPacket-based communicationsIndividual packets transmittedConnectionless serviceUses UDP (User Datagram Protocol)524.1 Introduction (Cont.)Client-server relationshipClient requests some action be performedServer performs the action and responds to clientRequest-response modelCommon implementation: Web browsers and Web servers6Performance Tip 24.1Connectionless services generally offer greater performance but less reliability than connection-oriented services. 7TCP, 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.1824.2 Manipulating URLsHyperText Transfer Protocol (HTTP)Uses URIs (Uniform Resource Identifiers) to identify dataURLs (Uniform Resource Locators)URIs that specify the locations of documentsRefer to files, directories and complex objectsHTML document SiteSelector.html (Fig. 24.1)applet elementparam tagname attributevalue attribute9Fig.24.17 | HTML document to load SiteSelector applet. Declare param tags for the applet, each parameter has a name and a valueSiteSelector.htmlLines 5-1210Import classes in package java.netImport interface AppletContext from package java.net11When the user selects one of the Web sites listed in siteChooser, the program calls method valueChangedPass 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 containerDisplay in the current browser window the resource associated with URL newDocument12Use Applet method getParameter to obtain a Web site titleUse Applet method getParameter to obtain the Web site locationUse the location as the value of a new URL objectIf the location passed to the URL constructor is invalid, the URL constructor throws a MalformedURLException13Use Applet method getParameter to obtain the next site title141524.2 Manipulating URLsHTML framesSpecify target frame in method showDocument_blank_self_top16Error-Prevention Tip 24.1The 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. 1724.3 Reading a File on a Web ServerSwing GUI component JEditorPaneRender both plain text and HTML-formatted textAct as a simple Web browserRetrieves files from a Web server at a given URIHyperlinkEventsOccur when the user clicks a hyperlinkThree event typesHyperlinkEvent.EventType.ACTIVATEDHyperlinkEvent.EventType.ENTEREDHyperlinkEvent.EventType.EXITED18Import JEditPane from package javax.swing, import HyperlinkEvent and HyperlinkListener from package javax.swing.eventDeclare JEditorPane contentsArea, which will be used to display the contents of the file19Create JEditorPane using the no-argument constructorSet JEditorPane editable property to falseRegister a HyperlinkListener to handle HyperlinkEvents, which occur when the user clicks a hyperlink in the JEditorPaneMethod hyperlinkUpdate is called when a HyperlinkEvent occursUse HyperlinkEvent method getEventType to determine the type of the HyperlinkEventUse HyperlinkEvent method getURL to obtain the URL represented by the hyperlink20Invoke JEditorPane method setPage to download the document specified by location and display it in the JEditPane212223A JEditorPane generates HyperlinkEvents only if it is uneditable. Look-and-Feel Observation 24.12424.4 Establishing a Simple Server Using Stream SocketsFive steps to create a simple server in JavaStep 1: Create ServerSocket objectServerSocket server = new ServerSocket( portNumber, queueLength );Register an available port Specify a maximum number of clientsHandshake pointBinding the server to the portOnly one client can be bound to a specific port25Software Engineering Observation 24.1Port 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. 2624.4 Establishing a Simple Server Using Stream Sockets (Cont.)Five steps to create a simple server in JavaStep 2: Server listens for client connectionServer blocks until client connectsSocket connection = server.accept();Step 3: Sending and receiving dataOutputStream to send and InputStream to receive dataMethod getOutputStream returns Socket’s OutputStreamMethods getInputstream returns Socket’s InputStream2724.4 Establishing a Simple Server Using Stream Sockets (Cont.)Five steps to create a simple server in JavaStep 4: Process phaseServer and Client communicate via streamsStep 5: Close streams and connectionsMethod close28With 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.229With 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.330A 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 31Performance Tip 24.2In 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. 3224.5 Establishing a Simple Client Using Stream SocketsFour steps to create a simple client in JavaStep 1: Create a Socket to connect to serverSocket connection = new Socket ( serverAddress, port );Step 2: Obtain Socket’s InputStream and OutputstreamStep 3: Process information communicatedStep 4: Close streams and connection3324.6 Client/Server Interaction with Stream Socket ConnectionsClient/server chat applicationUses stream sockets Server waits for a client connection attemptClient connects to the serverSend and receive messagesClient or server terminates the connectionServer waits for the next client to connect34Import ServerSocket and Socket from package java.netDeclare ServerSocket server which waits for client connectionDeclare Socket connection which connects to the client3536Create ServerSocket at port 12345 with queue of length 100Wait for a client connectionAfter the connection is established, obtain references to the streams for the connectionSend the initial connection message to the client and process all messages received from the client37Use ServerSocket method accept to wait for a connection from a clientOutput the host name of the computer that made the connection using Socket method getInetAddress and InetAddress method getHostNameObtain Socket’s OutputStream and use it to initialize ObjectOutputStream Method flush empties output buffer and sends header information38Obtain Socket’s InputStream and use it to initialize ObjectInputStream Use ObjectInputStream method readObject to read a String from client39Method closeConnection closes streams and socketsInvoke Socket method close to close the socketUse ObjectOutputStream method writeObject to send a String to client40414243Common Programming Error 24.1Specifying a port that is already in use or specifying an invalid port number when creating a ServerSocket results in a BindException. 44Software Engineering Observation 24.5When 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. 45Performance Tip 24.3A 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. 46474849Create a Socket that will connect with port 12345 on the serverUse InetAddress static method getByName to obtain an InetAdress object containing the IP address specified as a command-line argument to the applicationDisplay a message indicating the name of the server computer to which the client has connectedMethod flush empties output buffer and sends header informationObtain Socket’s OutputStream and use it to initialize ObjectOutputStream 50Read a String object from serverInvoke Socket method close to close the socket51Use ObjectOutputStream method writeObject to send a String to server5253545524.7 Connectionless Client/Server Interaction with DatagramsConnectionless transmission with datagramsNo connection maintained with other computerBreak message into separate pieces and send as packetsMessage arrive in order, out of order or not at allReceiver puts messages in order and reads them56Use a DatagramSocket as our server57Use the DatagramSocket constructor that takes an integer port number argument to bind the server to a port where it can receive packets from clientsCreate a DatagramPacket in which a received packet of information can be storedUse DatagramSocket method receive to wait for a packet to arrive at the server58Use DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sentUse DatagramPacket method getPort to obtain the port number through which the host computer sent the packetUse DatagramPacket method getLength to obtain the number of bytes of data sentUse DatagramPacket method getData to obtain an byte array containing the dataCreate 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 packets59Use method send of DatagramSocket to send the packet over the network60Server window after packetof data is received from client6162Convert the String to a byte arrayCreate 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 waitingUse DatagramPacket method send to send the packet63Create a DatagramSocket for sending and receiving packets64Create a DatagramPacket to store received informationUse DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sentUse DatagramPacket method getPort to obtain the port number through which the host computer sent the packetUse DatagramPacket method getLength to obtain the number of bytes of data sentUse DatagramPacket method getData to obtain an byte array containing the data6566Client window after sending packet to Server and receivingpacket back from Server67Common Programming Error 24.2Specifying a port that is already in use or specifying an invalid port number when creating a DatagramSocket results in a SocketException. 6824.8 Client/Server Tic-Tac-Toe Using a Multithreaded ServerMultiple threadsServer uses one thread per playerAllow each player to play game independently697071Create array players with 2 elementsCreate ServerSocket to listen on port 1234572Loop twice, blocking at line 79 each time while waiting for a client connectionCreate a new Player object to manage the connection as a separate threadExecute the Player in the runGame thread pool73747576Get the streams to send and receive data77Format output notifying the other player of the moveCall Formatter method flush to force the output to the clientSend player’s mark78Send message indicating one player connected and waiting for another player to arriveBegin the game79Send message indicating player O connectedRead a moveCheck the moveSend message indicating the move is valid80Send message indicating the move is invalid8182838485Connect to the serverGet the streams to send and receive dataRead mark character from server86Loop continuallyRead and process messages from serverIf valid move, write message and set mark in square87If invalid move, display messageIf opponent moves, set mark in square8889Send the move to the server90919293Fig.24.17 | Sample outputs from the client/server Tic-Tac-Toe program. (Part 1 of 2.)94Fig.24.17 | Sample outputs from the client/server Tic-Tac-Toe program. (Part 2 of 2.) 9524.9 Security and the NetworkBy default, applets cannot perform file processingApplets often limited in machine accessApplets can communicate only with the machine from which it was originally downloadedJava Security APIDigitally signed appletsApplets given more privileges if from trusted source96
Các file đính kèm theo tài liệu này:
- javahtp7e_24_8029_8372.ppt