全部版块 我的主页
论坛 数据科学与人工智能 IT基础 JAVA语言开发
1481 0
2015-06-05
A Simple Network Client using Java

Example 5-4 is a simple network client program that does not use the URL class. Instead, it uses java.net.Socket to connect to server. It sends a line of text to the server, and then reads and prints out the server’s response. The main point of interest in this example is the introduction of the Socket class, which creates a stream-based network connection between a client and a server. To create a network connection to another host, you simply create a Socket, specifying the desired host and port. If there is a program (a server) running on the specified host and listening for connections on the specified port, the Socket( ) constructor returns a Socket object you can use to communicate with the server. (If there is not a server listening on the specified host and port, or if anything goes wrong—and many things can go wrong with networking—the Socket( ) constructor throws an exception.)

If you are not familiar with hosts and ports, think of the host as a post office and the port as a post-office box. Just as a post office has many different post-office boxes, any host on the network can run many different servers at a time. Different servers use different ports for their addresses. To establish a connection, you must specify both the correct host and the correct port. Many services have standard default ports. Web servers run on port 80, POP email servers run on port 110, and so on.

Once you have a Socket object, you are connected, across the network, to a server. The getInputStream( ) method of the socket returns anInputStream you can use to read bytes from the server, and getOutputStream( ) returns an OutputStream you can use to write bytes to the server. This is exactly what this Connect program does.

Despite its simplicity, our simple Connect client is actually useful in conjunction with simple network servers like “daytime” (port 13) and “finger” (port 79). For example, here is how you can use the program to find out the current time (daytime) and to find out who is logged on to a server (finger):

java je3.net.Connect time-a.nist.gov 13java je3.net.Connect rtfm.mit.edu 79
复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群