Documentation

The Java™ Tutorials
Hide TOC
All About Sockets关于套接字的一切
Trail: Custom Networking

Lesson: All About Sockets课程:关于套接字的一切

URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. URLURLConnection为访问Internet上的资源提供了一种相对高级的机制。Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.有时,您的程序需要较低级别的网络通信,例如,当您想要编写客户机-服务器应用程序时。

In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. 在客户机-服务器应用程序中,服务器提供一些服务,例如处理数据库查询或发送当前股票价格。The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. 客户机使用服务器提供的服务,要么向用户显示数据库查询结果,要么向投资者提出股票购买建议。The communication that occurs between the client and the server must be reliable. 客户端和服务器之间的通信必须可靠。That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it.也就是说,不能丢弃任何数据,数据必须以服务器发送数据的相同顺序到达客户端。

TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use to communicate with each other. TCP提供了一个可靠的点对点通信通道,Internet上的客户机-服务器应用程序使用该通道相互通信。To communicate over TCP, a client program and a server program establish a connection to one another. 为了通过TCP进行通信,客户机程序和服务器程序彼此建立连接。Each program binds a socket to its end of the connection. 每个程序都将一个套接字绑定到其连接端。To communicate, the client and the server each reads from and writes to the socket bound to the connection.为了通信,客户机和服务器分别读取和写入绑定到连接的套接字。

What Is a Socket?什么是套接字?

A socket is one end-point of a two-way communication link between two programs running on the network. 套接字是网络上运行的两个程序之间双向通信链路的一个端点。Socket classes are used to represent the connection between a client program and a server program. 套接字类用于表示客户端程序和服务器程序之间的连接。The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.java.net包提供了两个类——SocketServerSocket——分别实现连接的客户端和服务器端。

Reading from and Writing to a Socket从套接字读写

This page contains a small example that illustrates how a client program can read from and write to a socket.本页包含一个小示例,说明客户端程序如何读取和写入套接字。

Writing a Client/Server Pair编写客户机/服务器对

The previous page showed an example of how to write a client program that interacts with an existing server via a Socket object. 上一页展示了如何编写通过套接字对象与现有服务器交互的客户端程序的示例。This page shows you how to write a program that implements the other side of the connection—a server program.本页向您展示如何编写实现连接另一端的程序—服务器程序。


Previous page: Previous Lesson
Next page: What Is a Socket?