Step by step teach you how to use Java to implement WebSocket_Java _ scripting home

How to implement WebSocket in Java

Updated: May 19, 2023 11:19:27 Author: Present and past
websocket protocol is a new network protocol based on TCP, it realizes the full duplex communication between the browser and the server - allows the server to actively initiate information client,websocket is a persistent protocol,http is a non-persistent protocol, the following article mainly introduces how to use Java to achieve WebSo cket related information, the need of friends can refer to the next

Introduction to WebSocket

The WebSocket protocol enables Web and server interaction by providing full-duplex communication between the client and the server.

In a WebSocket application, the server publishes a WebSocket endpoint, and the client connects to the server using a url. Once the connection is established, the server and client can send messages to each other. Clients typically connect to a single server, which accepts connections from multiple clients.

1.1 WebSocket Protocol

The WebSocket protocol has two parts: handshake and transfer. The client establishes a connection by sending a handshake request to the server URL. Handshakes are compatible with existing HTTP-based infrastructure. The Web server interprets this as an upgraded HTTP connection request.

A handshake request for a client to establish a connection:

GET/path/to/websocket HTTP / 1.1 / endpoint Host: localhost Upgrade: websocket Connection: Upgrade the Sec - websocket - Key: xqBt3ImNzJbYqRINxEFlkg== Origin: http://localhost Sec-WebSocket-Version: 13

A server response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8=

As can be seen from the above request and response, the establishment of a WebSocket connection requires the client and server to maintain a Key as the connection credential.

The client sends a WebSocketKey to the server, and the server generates a WebSocketAccept based on the WebSocketKey and returns it to the client. The client performs the same operation on the WebSocketKey value. If the value matches the value returned by the server, the handshake succeeds. After the handshake, the client and server send messages to each other.

1.2 Message Types supported by WebSocket

WebSocket supports both text messages (UTF-8 encoding) and binary messages. The WebSocket control message consists of Close, Ping, and Pong. ping and pong may also contain application information.

webSocket endpoints have the following URI representation:

ws://host:port/path? query wss://host:port/path? query
  • ws stands for unencrypted connection, and the default port is 80
  • wss stands for encrypted connection and the default port is 443
  • path: Indicates the location of endpoints within the server
  • query: Path parameter information

Create a WebSocket program

The process for creating and deploying a WebSocket endpoint is as follows:

1. Create an endpoint class

2. Implement a lifecycle approach for endpoints

3. Add the business logic to the endpoint

4. Deploy the endpoint into the Web application

** Note: ** In contrast to servlets, WebSocket endpoint classes are instantiated multiple times, and the container creates an instance for each connection to the URI it deploys. Each instance is associated with a connection. Because only one thread executes code for an endpoint instance at any one time, it helps to keep the user state of each connection simple.

2.1 Life Cycle Approach

Three lifecycle methods are defined in the EndPoint class: onOpen, onClose, and onError

Create service classes using annotations

@ServerEndpoint("/echo") public class EchoEndpoint { @OnMessage public void onMessage(Session session, String msg) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { ... }}}

2.2 Service Logic Methods

@ServerEndpoint("/receive") public class ReceiveEndpoint { @OnMessage public void textMessage(Session session, String msg) { System.out.println("Text message: " + msg); } @OnMessage public void binaryMessage(Session session, ByteBuffer msg) { System.out.println("Binary message: " + msg.toString()); } @OnMessage public void pongMessage(Session session, PongMessage msg) { System.out.println("Pong message: " + msg.getApplicationData().toString()); }}

Note: A service class can have up to three OnMessage annotations, using one method for each message type: Text, Binary, Pong

2.3 Maintaining Customer Status

Sometimes in the program we may need to maintain some user parameters in the connection, WebSocket also provides such a service

The Session. GetUserProperties for user parameter information

If you want to store information that is common to all connected clients, you can use static variables, but you need the user to guarantee thread-safe access to the data.

@ServerEndpoint("/delayedecho") public class DelayedEchoEndpoint { @OnOpen public void open(Session session) { session.getUserProperties().put("previousMsg", " "); } @OnMessage public void message(Session session, String msg) { String prev = (String) session.getUserProperties() .get("previousMsg"); session.getUserProperties().put("previousMsg", msg); try { session.getBasicRemote().sendText(prev); } catch (IOException e) { ... }}}

2.4 Encoding and decoding of data format

Since client and server interactions may involve the conversion of data formats, Decoder and Encoder methods are provided.

Since only one of WebSocket's @Message annotations can be used to transfer Text or Binary information, this method Encoder is required for the most common Json->entity transformation parsing

Encoder.Text is used for text messages Encoder.Binary is used for binary messages

How to use:

1. Create a codec class

public class MessageATextEncoder implements Encoder.Text<MessageA> { @Override public void init(EndpointConfig ec) { } @Override public void destroy() { } @Override public String encode(MessageA msgA) throws EncodeException { // Access msgA's properties and convert to JSON text... return msgAJsonString; }}

2. Add the Encoder to the endpoint class annotation

@ServerEndpoint(
   value = "/myendpoint",
   encoders = { MessageATextEncoder.class, MessageBTextEncoder.class }
)
public class EncEndpoint { ... }

3. MessageA and MessageB Text data can be sent

MessageA msgA = new MessageA(...) ; MessageB msgB = new MessageB(...) ; session.getBasicRemote.sendObject(msgA); session.getBasicRemote.sendObject(msgB);

Note: webSocket automatically finds which encoder to use, so send data using sendObject

Decoder

Implement Decoder to convert WebSocket messages into Java objects

Decoder.Text is used for text messages

Decoder.Binary is used for binary messages

Usage method

Similar to Encoder

Note: Unlike encoders, decoders can specify up to one Binary and one Text type Decoder, if there are more than two Java types sent and received as text messages that need to be defined. Multiple messages can inherit from a common message superclass

1. Write the Decoder class to decode different types of messages received

public class MessageTextDecoder implements Decoder.Text<Message> { @Override public void init(EndpointConfig ec) { } @Override public void destroy() { } @Override public Message decode(String string) throws DecodeException { // Read message... if ( /* message is an A message */ ) return new MessageA(...) ; else if ( /* message is a B message */ ) return new MessageB(...) ; } @Override public boolean willDecode(String string) { // Determine if the message can be converted into either a // MessageA object or a MessageB object... return canDecode; }}

2. Add decoders={MessageDecoder.class} to the endpoint class

@ServerEndpoint(
   value = "/myendpoint",
   encoders = { MessageATextEncoder.class, MessageBTextEncoder.class },
   decoders = { MessageTextDecoder.class }
)
public class EncDecEndpoint { ... }

3. Use in the @OnMessage method

@OnMessage public void message(Session session, Message msg) { if (msg instanceof MessageA) { // We received a MessageA object... } else if (msg instanceof MessageB) { // We received a MessageB object... }}

Sum up

To this article on how to use Java to achieve WebSocket article is introduced to this, more related Java to achieve WebSocket content please search the script home previous articles or continue to browse the following related articles hope that you will support the script home in the future!

Related article

Latest comments