How to implement WebSocket in Java
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!
- java based on websocket im chat function
- How to use Java to implement WebSocket
- The java back end + front end uses WebSocket to implement the detailed flow of message push
- java WebSocket server implementation code
- java WebSocket client disconnection reconnection method
- Java implement WebSocket in four steps
Related article
-
Java synchronize thread safety testing
This article mainly introduces Java thread safety test synchronize. This article introduces the sample code in detail. It has certain reference value for your study or work2020-04-04 -
Resolved mybatis case when an error was reported
This article mainly introduces to solve the problem of mybatis case when reporting errors, has a good reference value, I hope to help you. Let's take a look2021-02-02 -
java graphical interface addition calculator
This article mainly introduces the java graphical interface addition calculator in detail, the example code in the article is very detailed, has a certain reference value, interested partners can refer to it2022-04-04 -
JavaWeb form registration interface implementation
This article mainly introduces the JavaWeb form registration interface implementation method of the relevant information, I hope that through this article we can master this part of the content, the need of friends can refer to2017-09-09 -
Recently just started to learn maven, is preparing to use idea to create a maven project practice, but found that their own maven project has no src directory, the following article mainly introduces you about the IDEA to create Maven project after the error does not appear src folder solution, need friends can refer to2023-05-05
-
Example Java Class parser implementation method
This article mainly through the analysis of the class file, introduced the Java Class parser implementation method example, has a certain reference value, the need of friends can understand.2017-09-09 -
springboot Specifies the steps for reading parameters in the configuration file
In this article, Xiaobian has shared the relevant knowledge content about springboot reading the parameters in the configuration file, and the friends who need to follow it.2019-06-06 -
java interprets an example of whether there are duplicate values in an array
This article mainly introduces the java interpretation array whether there are duplicate values of the example, the need for friends can refer to the next2014-04-04 -
Three methods of yml multi-environment configuration in SpringBoot
This article mainly introduces three methods of yml multi-environment configuration in SpringBoot, and there are detailed code examples for your reference, which will be helpful to your study or work, and you can refer to your friends who need it2023-10-10 -
java string interception method substring() code parsing
This article mainly introduces the java string interception method substring() code analysis, the article through the example code introduction is very detailed, for everyone's study or work has a certain reference learning value, need friends can refer to it2020-02-02
Latest comments