//img.uscri.be/pth/eb42c16c67a5854b5e80e05cc7ebb3b979450044
La lecture en ligne est gratuite
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
Télécharger Lire

JavaNetworking-Tutorial

42 pages
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 Java Networking - Tutorial URLs and sockets N.B.: questo tutorial e' stato ottenuto per cut-and-paste di materiale contenuto nel sito: http://java.sun.com/docs/books/tutorial/networking/. Sono stati rimossi alcuni errori nella sezione 3.1. Table of Contents 1 Overview of Networking............................................................................................... 2 1.1 What You May Already Know About Networking in Java....................................... 2 1.1.1 Loading Applets from the Network .................................................................. 3 1.1.2 Loading Images from URLs ............................................................................. 3 1.2 Networking Basics................................................................................................... 3 1.2.1 TCP .................................................................................................................. 4 1.2.2 UDP.................................................................................................................. 4 1.2.3 Understanding Ports ........................................................................................ 5 1.2.4 Networking Classes in the JDK ....................................................................... 6 2 Working with URLs.................... ...
Voir plus Voir moins
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 Java Networking - Tutorial URLs and sockets
N.B.: questo tutorial e' stato ottenuto per cut-and-paste di materiale contenuto nel sito:va.aus.noc/modschttp://jikrowten/gn/tksoo/bl/iaorut. Sono stati rimossi alcuni errori nella sezione 3.1.
Table of Contents 1Overview of Networking............................................................................................... 21.1What You May Already Know About Networking in Java....................................... 21.1.1Loading Applets from the Network .................................................................. 31.1.2 Loading Images from URLs ............................................................................. 31.2Networking Basics ................................................................................................... 31.2.1TCP .................................................................................................................. 41.2.2 4UDP ..................................................................................................................1.2.3Understanding Ports ........................................................................................ 51.2.4Networking Classes in the JDK ....................................................................... 62Working with URLs....................................................................................................... 62.1What Is a URL? ....................................................................................................... 72.2Creating a URL........................................................................................................ 92.2.1Creating a URL Relative to Another ................................................................ 92.2.2Other URL Constructors ................................................................................ 102.2.3MalformedURLException ............................................................................... 102.3Parsing a URL ....................................................................................................... 112.4Reading Directly from a URL ................................................................................ 122.5Connecting to a URL ......................... .... 13................................................................ 2.6Reading from and Writing to a URLConnection ................................................... 132.6.1Reading from a URLConnection.................................................................. 3.. 1 2.6.2Writing to a URLConnection .......................................................................... 14
aJevNetworking:URLs&sockets1
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 3All About Sockets ....................................................................................................... 173.1What Is a Socket? ................................................................................................. 173.2 19 ..................................................................Reading from and Writing to a Socket3.3 21Writing the Server Side of a Socket ......................................................................3.3.1The Knock Knock Server ............................................................................... 223.3.2The Knock Knock Protocol ............................................................................ 24 3.3.3The Knock Knock Client................................................................................. 263.3.4 28Running the Programs ...................................................................................3.3.5 29Supporting Multiple Clients ............................................................................4 31 ..................................................................................................All About Datagrams4.1What Is a Datagram? ............................................................................................ 314.2 32Writing a Datagram Client and Server ..................................................................4.2.1TheQuoteServerClass .............................................................................. 324.2.2TheQuoteServerThreadClass................................................................. 334.2.3TheQuoteClient 36Class ..............................................................................4.2.4Running the Server and Client....................................................................... 384.3Broadcasting to Multiple Recipients...................................................................... 38
1 Overview of Networking Before plowing through the examples in the next several lessons, you should have an understanding of some networking basics. Also, to boost your confidence, we've included a section that reviews what you may already know about networking in Java without even realizing it. What You May Already Know About Networking in JavaIf you've been working on the other trails in this tutorial, you've probably loaded an applet over the Internet by now, and you've likely loaded images from the network into applets running over the network. All of this is using the network and you already know how to do it. This page highlights the networking features that are covered in other trails and lessons of this tutorial--features that you might already be familiar with--and provides links to the pages that discuss those features. Networking BasicsYou'll learn what you need to know about TCP, UDP, sockets, datagrams, and ports to get the most out of the remaining lessons in this trail. If you are already familiar with these concepts, feel free to skip this section.
1.1 What You May Already Know About Networking in Java The wordnetworking strikes fear in the hearts of many programmers. Fear not! Using the networking capabilities provided in the Java environment is quite easy. In fact, you may be using the network already without even realizing it!
aJevNetwroking:RULs&sockets2
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 1.1.1 Loading Applets from the Network If you have access to a Java-enabled browser, you have undoubtedbly already executed many applets. The applets you've run are referenced by a special tag in an HTML file  the<APPLET>tag. Applets can be located anywhere, whether on your local machine or somewhere out on the Internet. The location of the applet is completely invisible to you, the user. However, the location of the applet is encoded within the<APPLET>tag. The browser decodes this information, locates the applet, and runs it. If the applet is on some machine other than your own, the browser must download the applet before it can be run. This is the highest level of access that you have to the Internet from the Java development environment. Someone else has taken the time to write a browser that does all of the grunt work of connecting to the network and getting data from it, thereby enabling you to run applets from anywhere in the world. For more information:Your First Cup of Javawrite your first applet and run it.shows you how to TheWriting Appletstrail describes how to write Java applets from A to Z.
1.1.2 Loading Images from URLs If you've ventured into writing your own Java applets and applications, you may have run into a class in thejava.netcalled URL. This class represents a Uniform  package Resource Locator and is the address of some resource on the network. Your applets and applications can use a URL to reference and even connect to resources out on the network. For example, to load an image from the network, your Java program must first create a URL that contains the address to the image. This is the next highest level of interaction you can have with the Internet  your Java program gets an address of something it wants, creates a URL for it, and then uses some existing function in the Java development environment that does the grunt work of connecting to the network and retrieving the resource. For more information:How to Use Iconsshows you how to load an image into your Java program (whether applets or applications) when you have its URL. Before you can load the image you must create a URL object with the address of the resource in it. Working with URLs, the next lesson in this trail, provides a complete discussion about URLs, including how your programs can connect to them and read from and write to that connection.
1.2 Networking Basics Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
aJeveNtworikng:URLs&sockets3
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12
When you write Java programs that communicate over the network, you are programming at the application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in thejava.netpackage. These classes provide system-independent network communication. However, to decide which Java classes your programs should use, you do need to understand how TCP and UDP differ. 1.2.1 TCP When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection. This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and she answers. You send data back and forth over the connection by speaking to one another over the phone lines. Like the phone company, TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported. TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. The order in which the data is sent and received over the network is critical to the success of these applications. When HTTP is used to read from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a jumbled HTML file, a corrupt zip file, or some other invalid information. Definition:TCP(Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.
1.2.2 UDP The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, calleddatagrams, from one application to another. Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.
JaveNetworking:URLs&oskcets4
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 Definition:UDP(User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP. For many applications, the guarantee of reliability is critical to the success of the transfer of information from one end of the connection to the other. However, other forms of communication don't require such strict standards. In fact, they may be slowed down by the extra overhead or the reliable connection may invalidate the service altogether. Consider, for example, a clock server that sends the current time to its client when requested to do so. If the client misses a packet, it doesn't really make sense to resend it because the time will be incorrect when the client receives it on the second try. If the client makes two requests and receives packets from the server out of order, it doesn't really matter because the client can figure out that the packets are out of order and make another request. The reliability of TCP is unnecessary in this instance because it causes performance degradation and may hinder the usefulness of the service. Another example of a service that doesn't need the guarantee of a reliable channel is the ping command. The purpose of the ping command is to test the communication between two programs over the network. In fact, ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is. A reliable channel would invalidate this service altogether. The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data from one application to another. Sending datagrams is much like sending a letter through the mail service: The order of delivery is not important and is not guaranteed, and each message is independent of any others. Note: Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system administrator if UDP is permitted.
1.2.3 Understanding Ports Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use ofports. Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application. In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to
aJeveNwtorikng:URLs&oskcets5
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 receive all data destined for that port. A client can then rendezvous with the server at the server's port, as illustrated here:
Definition: The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are calledwell-known ports. Your applications should not attempt to bind to them. 1.2.4 Networking Classes in the JDK Through the classes injava.net, Java programs can use TCP or UDP to communicate over the Internet. TheURL,URLConnection,Socket, and ServerSocket classesall use TCP to communicate over the network. The DatagramPacket,DatagramSocket, andMulticastSocket are for use classes with UDP.
2 Working with URLs URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the Internet. You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.
JaveeNwtroikgn:RULs&sockets6
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class calledURLin the java.netpackage to represent a URL address. Terminology Note: The termURLcan be ambiguous. It can refer to an Internet address or aURLobject in a Java program. Where the meaning of URL needs to be specific, this text uses "URL address" to mean an Internet address andURL" object" to refer to an instance of theURLclass in a program.
What Is a URL?A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource. Creating a URLWithin your Java programs, you can create a URL object that represents a URL address. The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components. Parsing a URLGone are the days of parsing a URL to find out the host name, filename, and other information. With a valid URL object you can call any of its accessor methods to get all of that information from the URL without doing any string parsing! Reading Directly from a URLThis section shows how your Java programs can read from a URL using the openStream()method. Connecting to a URLIf you want to do more than just read from a URL, you can connect to it by calling openConnection() on the URL. TheopenConnection() returns a method URLConnection object that you can use for more general communications with the URL, such as reading from it, writing to it, or querying it for content and other information. Reading from and Writing to a URLConnectionSome URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL. For example, a search script may require detailed query data to be written to the URL before the search can be performed. This section shows you how to write to a URL and how to get results back.
2.1 What Is a URL? If you've been surfing the Web, you have undoubtedly heard the term URL and have used URLs to access HTML pages from the Web. It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World Wide Web because most URLs refer to a file on some machine on the
JaveNetworking:RULs&sockets7
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 network. However, remember that URLs also can point to other resources on the network, such as database queries and command output.
aJevN
Definition: URL is an acronym forUniform Resource Locatorand is a reference (an address) to a resource on the Internet. The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems:
As in the previous diagram, a URL has two main components:  Protocol identifier Resource name Note that the protocol identifier and the resource name are separated by a colon and two forward slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents. HTTP is just one of many different protocols used to access different types of resources on the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News. The resource name is the complete address to the resource. The format of the resource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the components listed in the following table: Host Namemachine on which the resource lives.The name of the FilenameThe pathname to the file on the machine.NuPmorbterThe port number to which to connect (typically optional).ReferenceA reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).For many protocols, the host name and the filename are required, while the port number and reference are optional. For example, the resource name for an HTTP URL must specify a server on the network (Host Name) and the path to the document on that machine (Filename); it also can specify a port number and a reference. In the URL for the Java Web sitejava.sun.comis the host name and the trailing slash is shorthand for the file named/index.html.
tewroikng:RULs&sockets8
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 2.2 Creating a URL The easiest way to create aURL object is from aString represents the human- that readable form of the URL address. This is typically the form that another person will use for a URL. For example, the URL for the Gamelan site, which is a directory of Java resources, takes the following form: http://www.gamelan.com/In your Java program, you can use aStringcontaining this text to create aURLobject: URL gamelan = new URL("http://www.gamelan.com/"); TheURLobject created above represents anabsolute URL. An absolute URL contains all of the information necessary to reach the resource in question. You can also create URLobjects from arelative URLaddress.
2.2.1 Creating a URL Relative to Another A relative URL contains only enough information to reach the resource relative to (or in the context of) another URL. Relative URL specifications are often used within HTML files. For example, suppose you write an HTML file calledJoesHomePage.html. Within this page, are links to other pages,PicturesOfMe.htmlandMyKids.html, that are on the same machine and in the same directory asJoesHomePage.html. The links toPicturesOfMe.htmland MyKids.htmlfromJoesHomePage.htmlcould be specified just as filenames, like this: <a href="PicturesOfMe.html">Pictures of Me</a> <a href="MyKids.html">Pictures of My Kids</a> These URL addresses arerelative URLs. That is, the URLs are specified relative to the file in which they are contained--JoesHomePage.html. In your Java programs, you can create aURLobject from a relative URL specification. For example, suppose you know two URLs at the Gamelan site: http://www.gamelan.com/pages/Gamelan.game.html http://www.gamelan.com/pages/Gamelan.net.html You can createURL objectsthese pages relative to their common base URL: for http://www.gamelan.com/pages/like this: URL gamelan = new URL("http://www.gamelan.com/pages/"); URL gamelanGames = new URL(gamelan, "Gamelan.game.html"); URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html"); This code snippet uses theURL constructor that lets you create aURL from object anotherURLobject (the base) and a relative URL specification. The general form of this constructor is: URL(URLbaseURL, StringrelativeURL) The first argument is aURLobject that specifies the base of the newURL. The second argument is aStringthat specifies the rest of the resource name relative to the base. IfbaseURL is null, then this constructor treatsrelativeURL an absolute URL like
JaveeNwtroikgn:URLs&sockets9
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 specification. Conversely, ifrelativeURL an absolute URL specification, then the is constructor ignoresbaseURL. This constructor is also useful for creatingURLobjects for named anchors (also called references) within a file. For example, suppose theGamelan.network.htmlfile has a named anchor calledBOTTOMat the bottom of the file. You can use the relative URL constructor to create aURLobject for it like this: URL gamelanNetworkBottom = new URL(gamelanNetwork, "#BOTTOM");
2.2.2 Other URL Constructors TheURL class provides two additional constructors for creating aURL object. These constructors are useful when you are working with URLs, such as HTTP URLs, that have host name, filename, port number, and reference components in the resource name portion of the URL. These two constructors are useful when you do not have a String containing the complete URL specification, but you do know various components of the URL. For example, suppose you design a network browsing panel similar to a file browsing panel that allows users to choose the protocol, host name, port number, and filename. You can construct aURLfrom the panel's components. The first constructor creates a URLobject from a protocol, host name, and filename. The following code snippet creates aURLto theGamelan.net.htmlfile at the Gamelan site: new URL("http", "www.gamelan.com", "/pages/Gamelan.net.html"); This is equivalent to new URL("http://www.gamelan.com/pages/Gamelan.net.html"); The first argument is the protocol, the second is the host name, and the last is the pathname of the file. Note that the filename contains a forward slash at the beginning. This indicates that the filename is specified from the root of the host. The finalURLthe port number to the list of arguments used in theconstructor adds previous constructor: URL gamelan = new URL("http", "www.gamelan.com", 80,  "pages/Gamelan.network.html"); This creates aURLobject for the following URL: http://www.gamelan.com:80/pages/Gamelan.network.html If you construct aURL objectof these constructors, you can get a using one Stringcontaining the complete URL address by using theURL object'stoString method or the equivalenttoExternalFormmethod.
2.2.3 MalformedURLException Each of the fourURL throws a constructorsMalformedURLException the if arguments to the constructor refer to anullor unknown protocol. Typically, you want to catch and handle this exception by embedding your URL constructor statements in a try/catchpair, like this:
JaveNetwroikng:RULs&sockets10
Universita' di Bologna, II Facolta' di Ingegneria Reti di Calcolatori, materiale didattico: annesso alle Lezioni 4 e 12 try {  URL myURL = new URL(. . .) } catch (MalformedURLException e) {  . . .  //exception handler code here . . . } SeeHandling Errors with Exceptionsfor information about handling exceptions.
Note:URLs are "write-once" objects. Once you've created aURL object, you cannot change any of its attributes (protocol, host name, filename, or port number).
2.3 Parsing a URL TheURLclass provides several methods that let you queryURLobjects. You can get the protocol, host name, port number, and filename from a URL using these accessor methods: getProtocolReturns the protocol identifier component of the URL. getHostReturns the host name component of the URL. getPortReturns the port number component of the URL. ThegetPortmethod returns an integer that is the port number. If the port is not set,getPortreturns -1. getFileReturns the filename component of the URL. getRefReturns the reference component of the URL.
aJevN
Note: Remember that not all URL addresses contain these components. The URL class provides these methods because HTTP URLs do contain these components and are perhaps the most commonly used URLs. The URL class is somewhat HTTP-centric. You can use thesegetXXXmethods to get information about the URL regardless of the constructor that you used to create the URL object. The URL class, along with these accessor methods, frees you from ever having to parse URLs again! Given any string specification of a URL, just create a new URL object and call any of the accessor methods for the information you need. This small example program creates a URL from a string specification and then uses the URL object's accessor methods to parse the URL: import java.net.*; import java.io.*;
teworikng:URLs&sockets11