首页 socket开发指南

socket开发指南

举报
开通vip

socket开发指南 Java sockets 101 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Soc...

socket开发指南
Java sockets 101 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Socket basics 3 3. An undercover socket 8 4. A simple example 11 5. A multithreaded example 18 6. A pooled example 21 7. Sockets in real life 27 8. Summary 31 9. Appendix 32 Java sockets 101 Page 1 Section 1. Tutorial tips Should I take this tutorial? Sockets, which provide a mechanism for communication between two computers, have been around since long before the Java language was a glimmer in James Gosling's eye. The language simply lets you use sockets effectively without having to know the details of the underlying operating system. Most books that focus on Java coding either fail to cover the topic, or leave a lot to the imagination. This tutorial will tell you what you really need to know to start using sockets effectively in your Java code. Specifically, we'll cover: * What sockets are * Where they fit into the structure of programs you're likely to write * The simplest sockets implementation that could possibly work -- to help you understand the basics * A detailed walkthrough of two additional examples that explore sockets in multithreaded and pooled environments * A brief discussion of an application for sockets in the real world If you can describe how to use the classes in the java.net package, this tutorial is probably a little basic for you, although it might be a good refresher. If you have been working with sockets on PCs and other platforms for years, the initial sections might bore you. But if you are new to sockets, and simply want to know what they are and how to use them effectively in your Java code, this tutorial is a great place to start. Getting help For questions about the content of this tutorial, contact the authors, Roy Miller (at rmiller@rolemodelsoft.com ) or Adam Williams (at awilliams@rolemodelsoft.com ). Roy Miller and Adam Williams are Software Developers at RoleModel Software, Inc. They have worked jointly to prototype a socket-based application for the TINI Java platform from Dallas Semiconductor. Roy and Adam are currently working on porting a COBOL financial transaction system to the Java platform, using sockets. Prior to joining RoleModel, Roy spent six years with Andersen Consulting (now Accenture) developing software and managing projects. He co-authored Extreme Programming Applied: Playing to Win (Addison-Wesley XP Series) scheduled for publication in October 2001. Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 2 Section 2. Socket basics Introduction Most programmers, whether they're coding in the Java language or not, don't want to know much about low-level details of how applications on different computers communicate with each other. Programmers want to deal with higher-level abstractions that are easier to understand. Java programmers want objects that they can interact with via an intuitive interface, using the Java constructs with which they are familiar. Sockets live in both worlds -- the low-level details that we'd rather avoid and the abstract layer we'd rather deal with. This section will explore just enough of the low-level details to make the abstract application understandable. Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 3 Computer networking 101 Computers operate and communicate with one another in a very simple way. Computer chips are a collection of on-off switches that store and transmit data in the form of 1s and 0s. When computers want to share data, all they need to do is stream a few million of these bits and bytes back and forth, while agreeing on speed, sequence, timing, and such. How would you like to worry about those details every time you wanted to communicate information between two applications? To avoid that, we need a set of packaged protocols that can do the job the same way every time. That would allow us to handle our application-level work without having to worry about the low-level networking details. These sets of packaged protocols are called stacks. The most common stack these days is TCP/IP. Most stacks (including TCP/IP) adhere roughly to the International Standards Organization (ISO) Open Systems Interconnect Reference Model (OSIRM). The OSIRM says that there are seven logical layers in a reliable framework for computer networking (see the diagram). Companies all over have contributed something that implements some of the layers in this model, from generating the electrical signals (pulses of light, radio frequency, and so on) to presenting the data to applications. TCP/IP maps to two layers in the OSI model, as shown in the diagram. We won't go into the details of the layers too much, but we want you to be aware of where sockets fit. Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 4 Where sockets fit Sockets reside roughly at the Session Layer of the OSI model (see the diagram). The Session Layer is sandwiched between the application-oriented upper layers and the real-time data communication lower layers. The Session Layer provides services for managing and controlling data flow between two computers. As part of this layer, sockets provide an abstraction that hides the complexities of getting the bits and bytes on the wire for transmission. In other words, sockets allow us to transmit data by having our application indicate that it wants to send some bytes. Sockets mask the nuts and bolts of getting the job done. When you pick up your telephone, you provide sound waves to a sensor that converts your voice into electrically transmittable data. The phone is a human's interface to the telecommunications network. You aren't required to know the details of how your voice is transported, only the party to whom you would like to connect. In the same sense, a socket acts as a high-level interface that hides the complexities of transmitting 1s and 0s across unknown channels. Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 5 Exposing sockets to an application When you write code that uses sockets, that code does work at the Presentation Layer. The Presentation Layer provides a common representation of information that the Application Layer can use. Say you are planning to connect your application to a legacy banking system that understands only EBCDIC. Your application domain objects store information in ASCII format. In this case, you are responsible for writing code at the Presentation Layer to convert data from EBCDIC to ASCII, and then (for example) to provide a domain object to your Application Layer. Your Application Layer can then do whatever it wants with the domain object. The socket-handling code you write lives only at the Presentation Layer. Your Application Layer doesn't have to know anything about how sockets work. What are sockets? Now that we know the role sockets play, the question remains: What is a socket? Bruce Eckel describes a socket this way in his book Thinking in Java: The socket is the software abstraction used to represent the "terminals" of a connection between two machines. For a given connection, there's a socket on each machine, and you can imagine a hypothetical "cable" running between the two machines with each end of the "cable" plugged into a socket. Of course, the physical hardware and cabling between machines is completely unknown. The whole point of the abstraction is that we don't have to know more than is necessary. In a nutshell, a socket on one computer that talks to a socket on another computer creates a communication channel. A programmer can use that channel to send data between the two machines. When you send data, each layer of the TCP/IP stack adds appropriate header information to wrap your data. These headers help the stack get your data to its destination. The good news is that the Java language hides all of this from you by providing the data to your code on streams, which is why they are sometimes called streaming sockets. Think of sockets as handsets on either side of a telephone call -- you and I talk and listen on our handsets on a dedicated channel. The conversation doesn't end until we decide to hang up (unless we're using cell phones). And until we hang up, our respective phone lines are busy. If you need to communicate between two computers without the overhead of higher-level mechanisms like ORBs (and CORBA, RMI, IIOP, and so on), sockets are for you. The low-level details of sockets get rather involved. Fortunately, the Java platform gives you Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 6 some simple yet powerful higher-level abstractions that make creating and using sockets easy. Types of sockets Generally speaking, sockets come in two flavors in the Java language: * TCP sockets (implemented by the Socket class, which we'll discuss later) * UDP sockets (implemented by the DatagramSocket class) TCP and UDP play the same role, but they do it differently. Both receive transport protocol packets and pass along their contents to the Presentation Layer. TCP divides messages into packets (datagrams) and reassembles them in the correct sequence at the receiving end. It also handles requesting retransmission of missing packets. With TCP, the upper-level layers have much less to worry about. UDP doesn't provide these assembly and retransmission requesting features. It simply passes packets along. The upper layers have to make sure that the message is complete and assembled in correct sequence. In general, UDP imposes lower performance overhead on your application, but only if your application doesn't exchange lots of data all at once and doesn't have to reassemble lots of datagrams to complete a message. Otherwise, TCP is the simplest and probably most efficient choice. Because most readers are more likely to use TCP than UDP, we'll limit our discussion to the TCP-oriented classes in the Java language. Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 7 Section 3. An undercover socket Introduction The Java platform provides implementations of sockets in the java.net package. In this tutorial, we'll be working with the following three classes in java.net: * URLConnection * Socket * ServerSocket There are more classes in java.net, but these are the ones you'll run across the most often. Let's begin with URLConnection. This class provides a way to use sockets in your Java code without having to know any of the underlying socket details. Using sockets without even trying The URLConnection class is the abstract superclass of all classes that create a communications link between an application and a URL. URLConnections are most useful for getting documents on Web servers, but can be used to connect to any resource identified by a URL. Instances of this class can be used both to read from and to write to the resource. For example, you could connect to a servlet and send a well-formed XML String to the server for processing. Concrete subclasses of URLConnection (such as HttpURLConnection) provide extra features specific to their implementation. For our example, we're not doing anything special, so we'll make use of the default behaviors provided by URLConnection itself. Connecting to a URL involves several steps: * Create the URLConnection * Configure it using various setter methods * Connect to the URL * Interact with it using various getter methods Next, we'll look at some sample code that demonstrates how to use a URLConnection to request a document from a server. The URLClient class We'll begin with the structure for the URLClient class. import java.io.*; import java.net.*; public class URLClient { protected URLConnection connection; public static void main(String[] args) { } public String getDocumentAt(String urlString) { } } Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 8 The first order of business is to import java.net and java.io. We give our class one instance variable to hold a URLConnection. Our class has a main() method that handles the logic flow of surfing for a document. Our class also has a getDocumentAt() method that connects to the server and asks it for the given document. We will go into the details of each of these methods next. Surfing for a document The main() method handles the logic flow of surfing for a document: public static void main(String[] args) { URLClient client = new URLClient(); String yahoo = client.getDocumentAt("http://www.yahoo.com"); System.out.println(yahoo); } Our main() method simply creates a new URLClient and calls getDocumentAt() with a valid URL String. When that call returns the document, we store it in a String and then print it out to the console. The real work, though, gets done in the getDocumentAt() method. Requesting a document from a server The getDocumentAt() method handles the real work of getting a document over the Web: public String getDocumentAt(String urlString) { StringBuffer document = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) document.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } return document.toString(); } The getDocumentAt() method takes a String containing the URL of the document we want to get. We start by creating a StringBuffer to hold the lines of the document. Next, we create a new URL with the urlString we passed in. Then we create a URLConnection and open it: URLConnection conn = url.openConnection(); Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 9 Once we have a URLConnection, we get its InputStream and wrap it in an InputStreamReader, which we then wrap in a BufferedReader so that we can read lines of the document we're getting from the server. We'll use this wrapping technique often when dealing with sockets in Java code, but we won't always discuss it in detail. You should be familiar with it before we move on: BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Having our BufferedReader makes reading the contents of our document easy. We call readLine() on reader in a while loop: String line = null; while ((line = reader.readLine()) != null) document.append(line + "\n"); The call to readLine() is going to block until in reaches a line termination character (for example, a newline character) in the incoming bytes on the InputStream. If it doesn't get one, it will keep waiting. It will return null only when the connection is closed. In this case, once we get a line, we append it to the StringBuffer called document, along with a newline character. This preserves the format of the document that was read on the server side. When we're done reading lines, we close the BufferedReader: reader.close(); If the urlString supplied to a URL constructor is invalid, a MalformedURLException is thrown. If something else goes wrong, such as when getting the InputStream on the connection, an IOException is thrown. Wrapping up Beneath the covers, URLConnection uses a socket to read from the URL we specified (which just resolves to an IP address), but we don't have to know about it and we don't care. But there's more to the story; we'll get to that shortly. Before we move on, let's review the steps to create and use a URLConnection: 1. Instantiate a URL with a valid URL String of the resource you're connecting to (throws a MalformedURLException if there's a problem). 2. Open a connection on that URL. 3. Wrap the InputStream for that connection in a BufferedReader so you can read lines. 4. Read the document using your BufferedReader. 5. Close your BufferedReader. You can find the complete code listing for URLClient at Code listing for URLClient on page 32 . Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 10 Section 4. A simple example Background The example we'll cover in this section illustrates how you can use Socket and ServerSocket in your Java code. The client uses a Socket to connect to a server. The server listens on port 3000 with a ServerSocket. The client requests the contents of a file on the server's C: drive. For the sake of clarity, we split the example into the client side and the server side. At the end, we'll put it all together so you can see the entire picture. We developed this code in IBM VisualAge for Java 3.5, which uses JDK 1.2. To create this example for yourself, JDK 1.1.7 or greater should be fine. The client and the server will run on a single machine, so don't worry about having a network available. Creating the RemoteFileClient class Here is the structure for the RemoteFileClient class: import java.io.*; import java.net.*; public class RemoteFileClient { protected String hostIp; protected int hostPort; protected BufferedReader socketReader; protected PrintWriter socketWriter; public RemoteFileClient(String aHostIp, int aHostPort) { hostIp = aHostIp; hostPort = aHostPort; } public static void main(String[] args) { } public void setUpConnection() { } public String getFile(String fileNameToGet) { } public void tearDownConnection() { } } First we import java.net and java.io. The java.net package gives you the socket tools you need. The java.io package gives you tools to read and write streams, which is the only way you can communicate with TCP sockets. We give our class instance variables to support reading from and writing to socket streams, and to store details of the remote host to which we will connect. The constructor for our class takes an IP address and a port number for a remote host and assigns them to instance variables. Our class has a main() method and three other methods. We'll go into the details of these methods later. For now, just know that setUpConnection() will connect to the remote server, getFile() will ask the remote server for the contents of fileNameToGet, and Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Java sockets 101 Page 11 tearDownConnection() will disconnect from the remote server. Implementing main() Here we implement the main() method, which will create the RemoteFileClient, use it to get the contents of a remote file, and then print the result: public static void main(String[] args) { RemoteFileClient remoteFileClient = new RemoteFileClient("127.0.0.1", 3000); remoteFileClient.setUpConnection(); String fileContents = remoteFileClient.getFile("C:\\WINNT\\Temp\\RemoteFile.txt"); remoteFileClient.tearDownConnection(); System.out.println(fileContents); } The main() method instantiates a new RemoteFileClient (the client) with an IP address and port number for the host. Then, we tell the client to set up a connection to the host (more on this later). Next, we tell the client to get the contents of a specified file on the host. Finally, we tell the client to tear down its connection to the host. We print out the contents of the file to the console, just to prove everything worked as planned. Setting up a connection Here we implement the setUpConnection() method, which will set up our Socket and give us ac
本文档为【socket开发指南】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_109695
暂无简介~
格式:pdf
大小:602KB
软件:PDF阅读器
页数:36
分类:互联网
上传时间:2010-01-13
浏览量:15