A Guide to the Java API for WebSocket – WebSocket的Java API指南

最后修改: 2017年 3月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

WebSocket provides an alternative to the limitation of efficient communication between the server and the web browser by providing bi-directional, full-duplex, real-time client/server communications. The server can send data to the client at any time. Because it runs over TCP, it also provides a low-latency low-level communication and reduces the overhead of each message.

WebSocket通过提供双向、全双工、实时的客户/服务器通信,为服务器和网络浏览器之间的高效通信限制提供了一种替代方案。服务器可以在任何时候向客户端发送数据。由于它在TCP上运行,它还提供了低延迟的低级通信,并减少了每个消息的开销.

In this article, we’ll take a look at the Java API for WebSockets by creating a chat-like application.

在这篇文章中,我们将通过创建一个类似于聊天的应用程序来了解WebSockets的Java API。

2. JSR 356

2.JSR 356

JSR 356 or the Java API for WebSocket, specifies an API that Java developers can use for integrating WebSockets withing their applications – both on the server side as well as on the Java client side.

JSR 356或Java API for WebSocket规定了一个API,Java开发人员可以使用该API将WebSockets集成到他们的应用程序中 – 在服务器端和Java客户端都是如此。

This Java API provides both server and client side components:

这个Java API同时提供了服务器和客户端的组件。

  • Server: everything in the javax.websocket.server package.
  • Client: the content of javax.websocket package, which consists of client side APIs and also common libraries to both server and client.

3. Building a Chat Using WebSockets

3.使用WebSockets建立一个聊天室

We will build a very simple chat-like application. Any user will be able to open the chat from any browser, type his name, login into the chat and start communicating with everybody connected to the chat.

我们将建立一个非常简单的类似聊天的应用程序。任何用户都可以从任何浏览器打开聊天,键入他的名字,登录到聊天中,并开始与连接到聊天的所有人交流。

We’ll start by adding the latest dependency to the pom.xml file:

我们将首先把最新的依赖关系添加到pom.xml文件。

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
</dependency>

The latest version may be found here.

最新的版本可以在这里找到。

In order to convert Java Objects into their JSON representations and vice versa, we’ll use Gson:

为了将Java Objects转换为其JSON表示,反之亦然,我们将使用Gson。

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>

The latest version is available in the Maven Central repository.

最新版本可在Maven Central资源库中找到。

3.1. Endpoint Configuration

3.1.端点配置

There are two ways of configuring endpoints: annotation-based and extension-based. You can either extend the javax.websocket.Endpoint class or use dedicated method-level annotations. As the annotation model leads to cleaner code as compared to the programmatic model, the annotation has become the conventional choice of coding. In this case, WebSocket endpoint lifecycle events are handled by the following annotations:

有两种配置端点的方法。基于注解的和基于扩展的。您可以扩展javax.websocket.Endpoint类或使用专用的方法级注解。由于与编程模式相比,注解模式会带来更简洁的代码,因此注解已成为编码的常规选择。在这种情况下,WebSocket端点生命周期事件由以下注释处理。

  • @ServerEndpoint: If decorated with @ServerEndpoint, the container ensures availability of the class as a WebSocket server listening to a specific URI space
  • @ClientEndpoint: A class decorated with this annotation is treated as a WebSocket client
  • @OnOpen: A Java method with @OnOpen is invoked by the container when a new WebSocket connection is initiated
  • @OnMessage: A Java method, annotated with @OnMessage, receives the information from the WebSocket container when a message is sent to the endpoint
  • @OnError: A method with @OnError is invoked when there is a problem with the communication
  • @OnClose: Used to decorate a Java method that is called by the container when the WebSocket connection closes

3.2. Writing the Server Endpoint

3.2.编写服务器端点

We declare a Java class WebSocket server endpoint by annotating it with @ServerEndpoint. We also specify the URI where the endpoint is deployed. The URI is defined relatively to the root of the server container and must begin with a forward slash:

我们通过使用@ServerEndpoint注释来声明一个Java类WebSocket服务器端点。我们还指定了部署该端点的URI。URI是相对于服务器容器的根定义的,必须以正斜杠开头。

@ServerEndpoint(value = "/chat/{username}")
public class ChatEndpoint {

    @OnOpen
    public void onOpen(Session session) throws IOException {
        // Get session and WebSocket connection
    }

    @OnMessage
    public void onMessage(Session session, Message message) throws IOException {
        // Handle new messages
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        // WebSocket connection closes
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        // Do error handling here
    }
}

The code above is the server endpoint skeleton for our chat-like application. As you can see, we have 4 annotations mapped to their respective methods. Below you can see the implementation of such methods:

上面的代码是我们类似聊天的应用程序的服务器端点骨架。正如你所看到的,我们有4个注解映射到它们各自的方法。下面你可以看到这些方法的实现。

@ServerEndpoint(value="/chat/{username}")
public class ChatEndpoint {
 
    private Session session;
    private static Set<ChatEndpoint> chatEndpoints 
      = new CopyOnWriteArraySet<>();
    private static HashMap<String, String> users = new HashMap<>();

    @OnOpen
    public void onOpen(
      Session session, 
      @PathParam("username") String username) throws IOException {
 
        this.session = session;
        chatEndpoints.add(this);
        users.put(session.getId(), username);

        Message message = new Message();
        message.setFrom(username);
        message.setContent("Connected!");
        broadcast(message);
    }

    @OnMessage
    public void onMessage(Session session, Message message) 
      throws IOException {
 
        message.setFrom(users.get(session.getId()));
        broadcast(message);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
 
        chatEndpoints.remove(this);
        Message message = new Message();
        message.setFrom(users.get(session.getId()));
        message.setContent("Disconnected!");
        broadcast(message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        // Do error handling here
    }

    private static void broadcast(Message message) 
      throws IOException, EncodeException {
 
        chatEndpoints.forEach(endpoint -> {
            synchronized (endpoint) {
                try {
                    endpoint.session.getBasicRemote().
                      sendObject(message);
                } catch (IOException | EncodeException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

When a new user logs in (@OnOpen) is immediately mapped to a data structure of active users. Then, a message is created and sent to all endpoints using the broadcast method.

当一个新用户登录时(@OnOpen)立即被映射到活动用户的数据结构中。然后,创建一个消息,并使用broadcast方法发送到所有端点。

This method is also used whenever a new message is sent (@OnMessage) by any of the users connected – this is the main purpose of the chat.

每当任何一个连接的用户发送新消息(@OnMessage)时,也会使用这个方法–这是聊天的主要目的。

If at some point an error occurs, the method with the annotation @OnError handles it. You can use this method to log the information about the error and clear the endpoints.

如果在某些时候发生了错误,带有注解的方法@OnError会处理它。你可以用这个方法来记录错误的信息,并清除端点。

Finally, when a user is no longer connected to the chat, the method @OnClose clears the endpoint and broadcasts to all users that a user has been disconnected.

最后,当用户不再连接到聊天时,方法@OnClose会清除端点并向所有用户广播用户已被断开连接。

4. Message Types

4.信息类型

The WebSocket specification supports two on-wire data formats – text and binary. The API supports both these formats, adds capabilities to work with Java objects and health check messages (ping-pong) as defined in the specification:

WebSocket规范支持两种线上数据格式–文本和二进制。该API支持这两种格式,增加了与规范中定义的Java对象和健康检查信息(ping-pong)一起工作的能力。

  • Text: Any textual data (java.lang.String, primitives or their equivalent wrapper classes)
  • Binary: Binary data (e.g. audio, image etc.) represented by a java.nio.ByteBuffer or a byte[] (byte array)
  • Java objects: The API makes it possible to work with native (Java object) representations in your code and use custom transformers (encoders/decoders) to convert them into compatible on-wire formats (text, binary) allowed by the WebSocket protocol
  • Ping-Pong: A javax.websocket.PongMessage is an acknowledgment sent by a WebSocket peer in response to a health check (ping) request

For our application, we’ll be using Java Objects. We’ll create the classes for encoding and decoding messages.

对于我们的应用程序,我们将使用Java Objects。我们将创建用于编码和解码消息的类。

4.1. Encoder

4.1.编码器

An encoder takes a Java object and produces a typical representation suitable for transmission as a message such as JSON, XML or binary representation. Encoders can be used by implementing the Encoder.Text<T> or Encoder.Binary<T> interfaces.

编码器接收一个Java对象并产生适合作为消息传输的典型表示,如JSON、XML或二进制表示。编码器可以通过实现Encoder.Text<T>Encoder.Binary<T>接口使用。

In the code below we define the class Message to be encoded and in the method encode we use Gson for encoding the Java object to JSON:

在下面的代码中,我们定义了要编码的类Message,在方法encode中,我们使用Gson将Java对象编码为JSON。

public class Message {
    private String from;
    private String to;
    private String content;
    
    //standard constructors, getters, setters
}
public class MessageEncoder implements Encoder.Text<Message> {

    private static Gson gson = new Gson();

    @Override
    public String encode(Message message) throws EncodeException {
        return gson.toJson(message);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
        // Custom initialization logic
    }

    @Override
    public void destroy() {
        // Close resources
    }
}

4.2. Decoder

4.2.解码器</strong

A decoder is the opposite of an encoder and is used to transform data back into a Java object. Decoders can be implemented using the Decoder.Text<T> or Decoder.Binary<T> interfaces.

解码器与编码器相反,用于将数据转换回一个Java对象。解码器可以使用Decoder.Text<T>Decoder.Binary<T>接口实现。

As we saw with the encoder, the decode method is where we take the JSON retrieved in the message sent to the endpoint and use Gson to transform it to a Java class called Message:

正如我们在编码器中看到的那样,decode 方法是我们从发送到端点的消息中获取JSON,并使用Gson将其转换为一个名为Message:的Java类。

public class MessageDecoder implements Decoder.Text<Message> {

    private static Gson gson = new Gson();

    @Override
    public Message decode(String s) throws DecodeException {
        return gson.fromJson(s, Message.class);
    }

    @Override
    public boolean willDecode(String s) {
        return (s != null);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
        // Custom initialization logic
    }

    @Override
    public void destroy() {
        // Close resources
    }
}

4.3. Setting Encoder and Decoder in Server Endpoint

4.3.在服务器端点设置编码器和解码器

Let’s put everything together by adding the classes created for encoding and decoding the data at the class level annotation @ServerEndpoint:

让我们把所有的东西放在一起,在类级注解@ServerEndpoint中加入为编码和解码数据而创建的类。

@ServerEndpoint( 
  value="/chat/{username}", 
  decoders = MessageDecoder.class, 
  encoders = MessageEncoder.class )

Every time messages are sent to the endpoint, they will automatically either be converted to JSON or Java objects.

每次消息被发送到端点时,它们将自动被转换为JSON或Java对象。

5. Conclusion

5.结论

In this article, we looked at what is the Java API for WebSockets and how it can help us building applications such as this real-time chat.

在这篇文章中,我们看了什么是WebSockets的Java API,以及它如何帮助我们建立诸如这种实时聊天的应用。

We saw the two programming models for creating an endpoint: annotations and programmatic. We defined an endpoint using the annotation model for our application along with the life cycle methods.

我们看到了创建端点的两种编程模式:注解和编程。我们使用注解模式为我们的应用程序和生命周期方法定义了一个端点。

Also, in order to be able to communicate back and forth between the server and client, we saw that we need encoders and decoders to convert Java objects to JSON and vice versa.

此外,为了能够在服务器和客户端之间来回通信,我们看到我们需要编码器和解码器来将Java对象转换成JSON,反之亦然。

The JSR 356 API is very simple and the annotation based programming model that makes it very easy to build WebSocket applications.

JSR 356 API非常简单,而且是基于注解的编程模型,使得构建WebSocket应用非常容易。

To run the application we built in the example, all we need to do is deploy the war file in a web server and go to the URL: http://localhost:8080/java-websocket/. You can find the link to the repository here.

要运行我们在例子中构建的应用程序,我们需要做的就是将战争文件部署在网络服务器中,然后进入URL。http://localhost:8080/java-websocket/。你可以在这里找到资源库的链接