wwweducn(烟台大苹果) 的 Blog

学习中的知识转载以及小量经验总结,仅此而已。

sdq ID:wwweducn
222888次访问,排名277好友0人,关注者0
wwweducn的文章
原创 109 篇
翻译 0 篇
转载 98 篇
评论 842 篇
烟台大苹果(wwweducn)的公告

与俺联系

我的GMAIL 我的LiveID

特别推荐

最近评论
wwweducn:www.infoxa.com有该书的下载
cookie:发个给我可以吗?谢谢了---zh.shan@yahoo.com.cn
hhdx:huanghundexing@163.com
jake:jake123.123@163.com
我也要一份.
谢谢了
zhangjiajun1982:建议看看这篇文章,写的更详细 http://www.150it.cn/bianchengwendang/netjishu/73008.html
文章分类
收藏
相册
两小无猜
BBS
两全其美
水木社区
blog博客
aprin的专栏
Casularm Blog
DBA-博客园
Everest的博客(RSS)
LileLTP-Java之路
SmallWhiteDragon
songshuweiba
俺老朱
分享Java快乐
北邮小硕
天外传音
我的google page
胡一刀
记忆人生
风中的飘絮
DataBase
ADP (Analyse, Design&Programmierung)
Akadia
Asktom
cnoug
Itpub
Ixora
Oracle example library
Tahiti
Friends'博客
十月天
小源
小白兔的家
蔡鸟的小窝
java学习
javafan
赛迪网
信息查询
IP Whois查询
万年历查询
很好呀-网址大全
时间校对
更多查询...
铁路时刻查询
存档
软件项目交易
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
订阅到BlogLines
订阅到Yahoo
订阅到GouGou
订阅到飞鸽
订阅到Rojo
订阅到newsgator
订阅到netvibes

原创 java网络编程入门1:Connecting to a Server(转自core java)收藏

新一篇: java网络编程入门2:Implementing Servers(转自core java) | 旧一篇: Chapter 3. Networking

Connecting to a Server

Before writing our first network program, let's learn about a great debugging tool for network programming that you already have, namely, telnet. Telnet is preinstalled on most systems (both UNIX and Windows). You should be able to launch it by typing telnet from a command shell.

You may have used telnet to connect to a remote computer, but you can use it to communicate with other services provided by Internet hosts as well. Here is an example of what you can do. Type

telnet time-A.timefreq.bldrdoc.gov 13

As Figure 3-1 shows, you should get back a line like this:

53221 04-08-04 02:19:40 50 0 0 513.0 UTC(NIST) *

Figure 3-1. Output of the "time of day" service


What is going on? You have connected to the "time of day" service that most UNIX machines constantly run. The particular server that you connected to is operated by the National Institute of Standards and Technology in Boulder, Colorado, and gives the measurement of a Cesium atomic clock. (Of course, the reported time is not completely accurate due to network delays.)

By convention, the "time of day" service is always attached to "port" number 13.

NOTE

In network parlance, a port is not a physical device, but an abstraction to facilitate communication between a server and a client (see Figure 3-2).

Figure 3-2. A client connecting to a server port



The server software is continuously running on the remote machine, waiting for any network traffic that wants to chat with port 13. When the operating system on the remote computer receives a network package that contains a request to connect to port number 13, it wakes up the listening server process and establishes the connection. The connection stays up until it is terminated by one of the parties.

When you began the telnet session with time-A.timefreq.bldrdoc.gov at port 13, an unrelated piece of network software knew enough to convert the string "time-A.timefreq.bldrdoc.gov" to its correct Internet Protocol address, 132.163.4.104. The software then sent a connection request to that computer, asking for a connection to port 13. Once the connection was established, the remote program sent back a line of data and then closed the connection. In general, of course, clients and servers engage in a more extensive dialog before one or the other closes the connection.

Here is another experiment, along the same lines, that is a bit more interesting. Do the following:

1.
Use telnet to connect to java.sun.com on port 80.

2.
Type the following, exactly as it appears, without pressing backspace. Note that there are spaces around the first slash but not the second.

3.
GET / HTTP/1.0

4.
Now, press the ENTER key two times.

Figure 3-3 shows the response. It should look eerily familiaryou got a page of HTML-formatted text, namely, the main web page for Java technology.

Figure 3-3. Using telnet to access an HTTP port


This is exactly the same process that your web browser goes through to get a web page. The only difference is that the browser displays the HTML code with nicer fonts.

Our first network program in Example 3-1 will do the same thing we did using telnetconnect to a port and print out what it finds.

Example 3-1. SocketTest.java
 1. import java.io.*;
 2. import java.net.*;
 3. import java.util.*;
 4.
 5. /**
 6.    This program makes a socket connection to the atomic clock
 7.    in Boulder, Colorado, and prints the time that the
 8.    server sends.
 9. */
10. public class SocketTest
11. {
12.    public static void main(String[] args)
13.    {
14.       try
15.       {
16.          Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
17.          try
18.          {
19.             InputStream inStream = s.getInputStream();
20.             Scanner in = new Scanner(inStream);
21.
22.             while (in.hasNextLine())
23.             {
24.                String line = in.nextLine();
25.                System.out.println(line);
26.             }
27.          }
28.          finally
29.          {
30.             s.close();
31.          }
32.       }
33.       catch (IOException e)
34.       {
35.          e.printStackTrace();
36.       }
37.    }
38. }

The key statements of this simple program are as follows:

Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
InputStream inStream = s.getInputStream();

The first line opens a socket, which is an abstraction for the network software that enables communication out of and into this program. We pass the remote address and the port number to the socket constructor. If the connection fails, then an UnknownHostException is thrown. If there is another problem, then an IOException occurs. Because UnknownHostException is a subclass of IOException and this is a sample program, we just catch the superclass.

Once the socket is open, the getInputStream method in java.net.Socket returns an InputStream object that you can use just like any other stream. (See Volume 1, Chapter 12 for information about streams.) Once you have grabbed the stream, this program simply:

  1. Uses a Scanner to read a line of characters sent by the server; and

  2. Prints each line out to standard output.

This process continues until the stream is finished and the server disconnects.

NOTE

This program works only with very simple servers, such as a "time of day" service. In more complex networking programs, the client sends request data to the server, and the server may not immediately disconnect at the end of a response. You will see how to implement that behavior in several examples throughout this chapter.


The Socket class is pleasant and easy to use because Java technology hides the complexities of establishing a networking connection and sending data across it. The java.net package essentially gives you the same programming interface you would use to work with a file.


java.net.Socket 1.0

  • Socket(String host, int port)

    constructs a socket to connect to the given host and port.

  • InputStream getInputStream()

  • OutputStream getOutputStream()

    get streams to read data from the socket and write data to the socket.

发表于 @ 2005年06月08日 20:42:00|评论(loading...)|编辑

新一篇: java网络编程入门2:Implementing Servers(转自core java) | 旧一篇: Chapter 3. Networking

评论

#xiaohua18866 发表于2006-04-07 01:20:00  IP: 202.103.243.*
Beautiful!
全力支持!
很感谢!
#xiaohua18866 发表于2006-04-07 01:21:00  IP: 202.103.243.*
爽快!
发表评论  


登录
Csdn Blog version 3.1a
Copyright © 烟台大苹果(wwweducn)