WeChat applet and Java implement websocket long connection

What is WebSocket long connection

WebSocket is a protocol for full-duplex communication over a single TCP connection. It does this by upgrading the HTTP protocol to the WebSocket protocol during the handshake phase. After a successful handshake, the client and server can push messages to each other without continuously initiating HTTP requests and responses.

WebSocket long connections are usually used in scenarios that require real-time push data or real-time chat.

How to implement WebSocket long connection in Java

Java implementations usually do this by implementing the WebSocket protocol. A basic sample code is provided below:

@ServerEndpoint("/websocket")
public class WebSocketServer {

    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("新连接:" + session.getId());
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到消息:" + message);
        // 进行业务处理...
        // 可以通过session.getBasicRemote().sendText()方法将处理结果返回给客户端
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭:" + session.getId());
        sessions.remove(session);
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}

In the above code, @ServerEndpoint("/websocket")the annotation is used to identify the current class as a WebSocket processing class. @OnOpenThe , @OnMessage, @OnClose, @OnErrorannotations respectively correspond to the four events of WebSocket, and will be triggered to execute the corresponding method when the corresponding event occurs.

You can write business processing code in @OnMessagethe method and session.getBasicRemote().sendText()return the processing results to the client through the method.

How to connect WeChat applet to WebSocket long connection

WebSocket connections can be created through the methods provided by the WeChat applet wx.connectSocket().

A sample code is provided below:

wx.connectSocket({
  url: 'wss://example.com/websocket',
  success: function() {
    console.log('连接成功');
  }
});

wx.onSocketOpen(function() {
  console.log('WebSocket连接已打开');
});

wx.onSocketMessage(function (res) {
  console.log('收到消息:', res.data);
});

wx.onSocketError(function (res) {
  console.log('WebSocket连接错误');
});

wx.onSocketClose(function () {
  console.log('WebSocket已关闭');
});

In wx.connectSocket()the method, urlthe parameter points to the address of the WebSocket server. In wx.onSocketOpen()the method, you can write the processing logic after the connection is successful, and in wx.onSocketMessage()the method, you can write the processing logic after the message is received.

Example description

Example 1: Chat room implementation

We can implement a simple chat room through Java WebSocket long connection and WeChat applet access.

On the Java side, we need to implement a WebSocket class similar to the example to handle WebSocket connections, send and receive messages, and connection closing events. At the same time, we also need to perform logical processing when receiving messages and push messages to all connections. WebSocket client to the server. Examples are as follows:

@ServerEndpoint("/websocket/chatroom")
public class ChatRoomWebSocketServer {

    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("新连接:" + session.getId());
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到消息:" + message);
        for (Session s : sessions) {
            try {
                s.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭:" + session.getId());
        sessions.remove(session);
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}

On the WeChat applet, we need to write two pages. chatroom/indexThe page is used to display chat room messages and send messages. index/indexThe page is used to obtain user information and communication keys.

chatroom/indexIn the page, we need to use wx.connectSocket()the method to connect to the Java WebSocket long-connect chat room service. At the same time, after a successful connection, we need to use the wx.sendSocketMessage()method to send a message similar to the following to the server:

{
  "type": "enter",
  "content": "加入聊天室"
}

On the Java side, we can perform corresponding logical processing by parsing the received message type and content. At the same time, we also need to push the received messages to all clients, such as the following code:

On chatroom/indexthe page, we need a listening wx.onSocketMessage()method. After receiving the message, render the message to the chat room page, for example, the following code:

wx.onSocketMessage(function (res) {
  var message = JSON.parse(res.data);

  switch(message.type) {
    case 'enter':
      // 新用户加入
      break;
    case 'normal':
      // 收到消息
      break;
    case 'leave':
      // 用户离开
      break;
  }
});

Example 2: Push data in real time

We can implement a sample application for real-time push data through Java WebSocket long connection and WeChat applet access.

On the Java side, we need to implement a WebSocket class similar to the example to handle WebSocket connections, send and receive messages, and connection closing events. At the same time, we also need to perform logical processing when receiving messages and push messages to all connections. WebSocket client to the server. Examples are as follows:

@ServerEndpoint("/websocket/realtime")
public class RealTimeWebSocketServer {

    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("新连接:" + session.getId());
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 接收数据并进行业务处理(省略代码)
        // 通过session.getBasicRemote().sendText()方法将处理结果返回给客户端
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭:" + session.getId());
        sessions.remove(session);
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 通过一个定时器向所有连接的客户端推送数据
     */
    public void pushData() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                for (Session session : sessions) {
                    try {
                        session.getBasicRemote().sendText(getData());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 0, 1000);
    }
}

On the WeChat applet, we need to use wx.connectSocket()methods to connect to the Java WebSocket long connection real-time push data service. After successful connection, we need to wx.sendSocketMessage()send corresponding messages to the server through methods to request data according to the needs of the application, such as the following message:

{
  "type": "getData",
  "content": {
    "id": "001",
    "type": "realtime"
  }
}

On the Java side, we can perform corresponding logical processing by parsing the received message type and content. For example, getDatareal-time data results can be returned after receiving a message.

On the WeChat applet, we need a listening wx.onSocketMessage()method to render the data into the page after receiving the message.

Conclusion

Through the combination of Java and WeChat applet to realize WebSocket long connection, we can easily implement functions such as real-time push and online chat in the application, making the application more in line with the user's usage habits and improving the user's experience of the application.

Guess you like

Origin blog.csdn.net/qq_27981847/article/details/132758767