1. Overview
1.概述
The term socket programming refers to writing programs that execute across multiple computers in which the devices are all connected to each other using a network.
术语socket 编程是指编写在多台计算机上执行的程序,其中的设备都是用网络相互连接的。
There are two communication protocols that we can use for socket programming: User Datagram Protocol (UDP) and Transfer Control Protocol (TCP).
有两种通信协议,我们可以用来进行套接字编程。用户数据报协议(UDP)和传输控制协议(TCP)。
The main difference between the two is that UDP is connection-less, meaning there’s no session between the client and the server, while TCP is connection-oriented, meaning an exclusive connection must first be established between the client and server for communication to take place.
两者之间的主要区别是,UDP是无连接的,意味着客户端和服务器之间没有会话,而TCP是面向连接的,意味着必须首先在客户端和服务器之间建立一个专属连接,才能进行通信。
This tutorial presents an introduction to sockets programming over TCP/IP networks, and demonstrates how to write client/server applications in Java. UDP isn’t a mainstream protocol, and as such, might not be encountered often.
本教程介绍了通过TCP/IP网络的套接字编程,并演示了如何用Java编写客户端/服务器应用程序。UDP并不是一个主流协议,因此可能不经常遇到。
2. Project Setup
2.项目设置
Java provides a collection of classes and interfaces that take care of low-level communication details between the client and server.
Java提供了一系列的类和接口,负责处理客户和服务器之间的低级通信细节。
These are mostly contained in the java.net package, so we need to make the following import:
这些大部分都包含在java.net包中,所以我们需要进行以下导入。
import java.net.*;
We also need the java.io package, which gives us input and output streams to write to and read from while communicating:
我们还需要java.io包,它为我们提供了输入和输出流,以便在通信时写入和读出。
import java.io.*;
For the sake of simplicity, we’ll run our client and server programs on the same computer. If we were to execute them on different networked computers, the only thing that would change is the IP address. In this case, we’ll use localhost on 127.0.0.1.
为了简单起见,我们将在同一台计算机上运行我们的客户和服务器程序。如果我们要在不同的联网计算机上执行它们,唯一会改变的就是IP地址。在这种情况下,我们将使用localhost在127.0.0.1。
3. Simple Example
3.简单的例子
Let’s get our hands dirty with the most basic of examples involving a client and a server. It’s going to be a two-way communication application where the client greets the server and the server responds.
让我们用最基本的例子来弄脏我们的手,涉及一个客户和一个服务器。这将是一个双向的通信应用,客户向服务器问好,服务器也会做出回应。
We’ll create the server application in a class called GreetServer.java with the following code.
我们将在一个名为GreetServer.java的类中创建服务器应用程序,代码如下。
We’ll include the main method and the global variables to draw attention to how we’ll be running all servers in this article. For the rest of the examples in this article, we’ll omit this kind of repetitive code:
我们将包括main方法和全局变量,以提请注意我们将在本文中运行所有服务器。对于本文中的其他例子,我们将省略这种重复的代码。
public class GreetServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String greeting = in.readLine();
if ("hello server".equals(greeting)) {
out.println("hello client");
}
else {
out.println("unrecognised greeting");
}
}
public void stop() {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) {
GreetServer server=new GreetServer();
server.start(6666);
}
}
We’ll also create a client called GreetClient.java with this code:
我们还将用这段代码创建一个名为GreetClient.java的客户端。
public class GreetClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) {
out.println(msg);
String resp = in.readLine();
return resp;
}
public void stopConnection() {
in.close();
out.close();
clientSocket.close();
}
}
Now let’s start the server. In our IDE, we do this by simply running it as a Java application.
现在让我们启动服务器。在我们的IDE中,我们通过简单地将其作为一个Java应用程序运行来实现这一目标。
Then we’ll send a greeting to the server using a unit test, which confirms the server sends a greeting in response:
然后我们将使用单元测试向服务器发送问候语,确认服务器发送问候语作为回应。
@Test
public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() {
GreetClient client = new GreetClient();
client.startConnection("127.0.0.1", 6666);
String response = client.sendMessage("hello server");
assertEquals("hello client", response);
}
This example gives us a feel for what to expect later in the article. As such, we might not yet completely understand what’s happening here.
这个例子让我们感受到了文章后面的内容。因此,我们可能还不能完全理解这里发生了什么。
In the following sections, we’ll dissect socket communication using this simple example, and dive into more complex ones as well.
在下面的章节中,我们将用这个简单的例子来剖析socket通信,同时也会深入研究更复杂的例子。
4. How Sockets Work
4.插座的工作原理
We’ll use the above example to step through different parts of this section.
我们将用上面的例子来逐步了解本节的不同部分。
By definition, a socket is one endpoint of a two-way communication link between two programs running on different computers on a network. A socket is bound to a port number so that the transport layer can identify the application that data is destined to be sent to.
根据定义,socket是网络上不同计算机上运行的两个程序之间的双向通信链接的一个端点。套接字被绑定到一个端口号上,以便传输层能够识别数据注定要被发送的应用程序。
4.1. The Server
4.1.服务器
Usually, a server runs on a specific computer on the network and has a socket that’s bound to a specific port number. In our case, we’ll use the same computer as the client, and start the server on port 6666:
通常情况下,服务器在网络上的特定计算机上运行,并有一个与特定端口号绑定的套接字。在我们的例子中,我们将使用与客户端相同的计算机,并在端口6666上启动服务器。
ServerSocket serverSocket = new ServerSocket(6666);
The server just waits, listening to the socket for a client to make a connection request. This happens in the next step:
服务器只是在等待,监听套接字,等待客户端发出连接请求。这发生在下一个步骤。
Socket clientSocket = serverSocket.accept();
When the server code encounters the accept method, it blocks until a client makes a connection request to it.
当服务器代码遇到accept方法时,它就会阻塞,直到有客户向它发出连接请求。
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket, clientSocket, bound to the same local port, 6666, and also has its remote endpoint set to the address and port of the client.
如果一切顺利,服务器接受该连接。接受后,服务器得到一个新的套接字,clientSocket,绑定到相同的本地端口,6666,并将其远程端点设置为客户端的地址和端口。
At this point, the new Socket object puts the server in direct connection with the client. We can then access the output and input streams to write and receive messages to and from the client respectively:
在这一点上,新的Socket对象使服务器与客户端直接连接。然后我们可以访问输出和输入流,分别向客户端写入和接收消息。
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Now the server is capable of exchanging messages with the client endlessly until the socket is closed with its streams.
现在,服务器能够无休止地与客户端交换信息,直到套接字与它的流关闭。
However, in our example, the server can only send a greeting response before it closes the connection. This means that if we ran our test again, the server would refuse the connection.
然而,在我们的例子中,服务器在关闭连接之前只能发送一个问候的回应。这意味着,如果我们再次运行我们的测试,服务器将拒绝连接。
To allow continuity in communication, we’ll have to read from the input stream inside a while loop, and only exit when the client sends a termination request. We’ll see this in action in the following section.
为了保证通信的连续性,我们必须在一个while循环中从输入流中读取数据,并且只有在客户端发出终止请求时才退出。我们将在下一节中看到这个动作。
For every new client, the server needs a new socket returned by the accept call. We use the serverSocket to continue to listen for connection requests, while tending to the needs of the connected clients. We haven’t yet allowed for this in our first example.
对于每个新的客户端,服务器需要一个由accept调用返回的新套接字。我们使用serverSocket来继续监听连接请求,同时照顾到已连接客户的需求。在我们的第一个例子中,我们还没有考虑到这一点。
4.2. The Client
4.2.客户
The client must know the hostname or IP of the machine on which the server is running, and the port number on which the server is listening.
客户端必须知道服务器所运行的机器的主机名或IP,以及服务器所监听的端口号。
To make a connection request, the client tries to rendezvous with the server on the server’s machine and port:
为了发出连接请求,客户试图在服务器的机器和端口上与服务器会合。
Socket clientSocket = new Socket("127.0.0.1", 6666);
The client also needs to identify itself to the server, so it binds to a local port number assigned by the system that it’ll use during this connection. We don’t deal with this ourselves.
客户端还需要向服务器确认自己的身份,因此它绑定了一个由系统分配的本地端口号,在这个连接过程中它将使用这个端口号。我们自己不处理这个问题。
The above constructor only creates a new socket when the server has accepted the connection; otherwise, we’ll get a connection refused exception. When successfully created, we can then obtain input and output streams from it to communicate with the server:
上述构造函数只在服务器接受连接时创建一个新的套接字;否则,我们将得到一个连接拒绝的异常。成功创建后,我们就可以从它那里获得输入和输出流,与服务器通信。
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
The input stream of the client is connected to the output stream of the server, just like the input stream of the server is connected to the output stream of the client.
客户端的输入流与服务器的输出流相连,就像服务器的输入流与客户端的输出流相连。
5. Continuous Communication
5.持续沟通
Our current server blocks until a client connects to it, and then blocks again to listen to a message from the client. After the single message, it closes the connection because we haven’t dealt with continuity.
我们目前的服务器一直阻塞,直到有客户连接到它,然后再次阻塞,以听取客户的消息。在听完一条消息后,它就关闭连接,因为我们还没有处理好连续性的问题。
As such, it’s only helpful in ping requests. But imagine that we’d like to implement a chat server; continuous back and forth communication between the server and client would definitely be required.
因此,它只对平移请求有帮助。但想象一下,我们想实现一个聊天服务器;服务器和客户端之间肯定需要连续的来回通信。
We’ll have to create a while loop to continuously observe the input stream of the server for incoming messages.
我们必须创建一个while循环,以持续观察服务器的输入流,寻找传入的信息。
So let’s create a new server called EchoServer.java, whose sole purpose is to echo back whatever messages it receives from clients:
因此,让我们创建一个名为EchoServer.java的新服务器,其唯一的目的是回显它从客户端收到的任何消息。
public class EchoServer {
public void start(int port) {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (".".equals(inputLine)) {
out.println("good bye");
break;
}
out.println(inputLine);
}
}
Notice that we added a termination condition, where the while loop exits when we receive a period character.
注意,我们添加了一个终止条件,当我们收到一个句号字符时,while循环就会退出。
We’ll start EchoServer using the main method, just as we did for the GreetServer. This time, we start it on another port, such as 4444, to avoid confusion.
我们将使用main方法启动EchoServer,就像我们对GreetServer做的那样。这一次,我们在另一个端口上启动它,例如4444,以避免混淆。
The EchoClient is similar to GreetClient, so we can duplicate the code. We’re separating them for clarity.
EchoClient与GreetClient类似,所以我们可以重复代码。为了清晰起见,我们把它们分开。
In a different test class, we’ll create a test to show that multiple requests to the EchoServer will be served without the server closing the socket. This is true as long as we’re sending requests from the same client.
在另一个测试类中,我们将创建一个测试,以显示对EchoServer的多个请求将被服务,而服务器不会关闭套接字。只要我们从同一个客户端发送请求,这就是真的。
Dealing with multiple clients is a different case, which we’ll see in a subsequent section.
处理多个客户是一个不同的情况,我们将在随后的章节中看到。
Now let’s create a setup method to initiate a connection with the server:
现在让我们创建一个setup方法来启动与服务器的连接。
@Before
public void setup() {
client = new EchoClient();
client.startConnection("127.0.0.1", 4444);
}
We’ll also create a tearDown method to release all our resources. This is best practice for every case where we use network resources:
我们还将创建一个tearDown方法来释放我们所有的资源。这是对我们使用网络资源的每一种情况的最佳做法。
@After
public void tearDown() {
client.stopConnection();
}
Then we’ll test our echo server with a few requests:
然后,我们将用几个请求来测试我们的回声服务器。
@Test
public void givenClient_whenServerEchosMessage_thenCorrect() {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
String resp3 = client.sendMessage("!");
String resp4 = client.sendMessage(".");
assertEquals("hello", resp1);
assertEquals("world", resp2);
assertEquals("!", resp3);
assertEquals("good bye", resp4);
}
This is an improvement over the initial example, where we’d only communicate once before the server closed our connection. Now we send a termination signal to tell the server when we’re done with the session.
与最初的例子相比,这是一个改进,在最初的例子中,我们只在服务器关闭我们的连接之前进行一次通信。现在我们发送一个终止信号来告诉服务器我们已经完成了会话。
6. Server With Multiple Clients
6.有多个客户的服务器
As much as the previous example was an improvement over the first one, it’s still not a great solution. A server must have the capacity to service many clients and many requests simultaneously.
尽管前面的例子比第一个例子有进步,但它仍然不是一个很好的解决方案。一个服务器必须有能力同时为许多客户和许多请求提供服务。
Handling multiple clients is what we’re going to cover in this section.
处理多个客户是我们在本节中要介绍的内容。。
Another feature we’ll see here is that the same client could disconnect and reconnect again, without getting a connection refused exception or a connection reset on the server. We weren’t previously able to do this.
我们在这里看到的另一个特点是,同一个客户端可以断开连接,然后再重新连接,而不会在服务器上得到一个连接拒绝的异常或连接重置。我们以前是不能这样做的。
This means that our server is going to be more robust and resilient across multiple requests from multiple clients.
这意味着我们的服务器将在来自多个客户的多个请求中变得更加强大和有弹性。
We’ll do this by creating a new socket for every new client and service that client’s request on a different thread. The number of clients being served simultaneously will equal the number of threads running.
我们将通过为每个新客户创建一个新的套接字,并在不同的线程上为该客户的请求提供服务。同时被服务的客户数量将等于运行的线程数量。
The main thread will be running a while loop as it listens for new connections.
主线程在监听新连接时将运行一个while循环。
Now let’s see this in action. We’ll create another server called EchoMultiServer.java. Inside it, we’ll create a handler thread class to manage each client’s communications on its socket:
现在让我们看看这个动作。我们将创建另一个名为EchoMultiServer.java.的服务器,在里面我们将创建一个处理程序线程类来管理每个客户在其套接字上的通信。
public class EchoMultiServer {
private ServerSocket serverSocket;
public void start(int port) {
serverSocket = new ServerSocket(port);
while (true)
new EchoClientHandler(serverSocket.accept()).start();
}
public void stop() {
serverSocket.close();
}
private static class EchoClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public EchoClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (".".equals(inputLine)) {
out.println("bye");
break;
}
out.println(inputLine);
}
in.close();
out.close();
clientSocket.close();
}
}
Notice that we now call accept inside a while loop. Every time the while loop is executed, it blocks on the accept call until a new client connects. Then the handler thread, EchoClientHandler, is created for this client.
请注意,我们现在在一个while循环中调用accept。每次执行while循环时,都会在accept调用上阻塞,直到有新的客户端连接。然后,处理线程EchoClientHandler就会为这个客户创建。
What happens inside the thread is the same as the EchoServer, where we handled only a single client. The EchoMultiServer delegates this work to EchoClientHandler so that it can keep listening for more clients in the while loop.
线程内部发生的事情与EchoServer相同,在那里我们只处理一个客户端。EchoMultiServer将这项工作委托给EchoClientHandler,因此它可以在while循环中继续监听更多的客户端。
We’ll still use EchoClient to test the server. This time, we’ll create multiple clients each sending and receiving multiple messages from the server.
我们仍将使用EchoClient来测试服务器。这一次,我们将创建多个客户端,每个客户端从服务器发送和接收多个消息。
Let’s start our server using its main method on port 5555.
让我们使用它的主方法在端口5555启动我们的服务器。
For clarity, we’ll still put tests in a new suite:
为了清楚起见,我们仍然会把测试放在一个新的套件中。
@Test
public void givenClient1_whenServerResponds_thenCorrect() {
EchoClient client1 = new EchoClient();
client1.startConnection("127.0.0.1", 5555);
String msg1 = client1.sendMessage("hello");
String msg2 = client1.sendMessage("world");
String terminate = client1.sendMessage(".");
assertEquals(msg1, "hello");
assertEquals(msg2, "world");
assertEquals(terminate, "bye");
}
@Test
public void givenClient2_whenServerResponds_thenCorrect() {
EchoClient client2 = new EchoClient();
client2.startConnection("127.0.0.1", 5555);
String msg1 = client2.sendMessage("hello");
String msg2 = client2.sendMessage("world");
String terminate = client2.sendMessage(".");
assertEquals(msg1, "hello");
assertEquals(msg2, "world");
assertEquals(terminate, "bye");
}
We could create as many of these test cases as we please, each spawning a new client, and the server will serve them all.
我们可以随心所欲地创建这些测试案例,每个案例都产生一个新的客户端,而服务器将为它们提供服务。
7. Conclusion
7.结论
In this article, we focused on an introduction to sockets programming over TCP/IP, and wrote a simple Client/Server application in Java.
在这篇文章中,我们重点介绍了通过TCP/IP的套接字编程,并用Java编写了一个简单的客户/服务器应用程序。
The full source code for this article can be found in the GitHub project.
这篇文章的完整源代码可以在GitHub项目中找到。