WebSocket details
WebSocket is a full duplex communication protocol provided by HTML5 on a single TCP connection.
WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, and they can directly create a persistent connection and carry out two-way data transmission. It can be said that the appearance of WebSocket makes the browser have the ability of real-time two-way communication
In WebSocket API, browser and server only need to make a handshake, and then a fast channel is formed between browser and server. The two can directly transmit data to each other.
Originally, in order to implement push, many companies use Ajax polling, that is, according to a specific time interval, the browser sends an HTTP request to the server, and then the server returns the latest data to the browser of the client. This traditional mode brings obvious disadvantages, that is, the browser needs to send requests to the server constantly, but HTTP requests may contain a long header, in which the real effective data may only be a small part, obviously this will waste a lot of bandwidth and other resources. websocket can solve these problems.
Using WebSocket in Spring Boot
1.pom files increase dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2. Add configuration
@Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3.Java code
@Component @ServerEndpoint("/websocket") public class WebSocketServerController { // Method called by received message @OnMessage public void onMessage(String message) { System.out.println("The message received is " + message); } // Methods for establishing connection calls @OnOpen public void onOpen() { System.out.println("Client connected"); } // Method to close connection call @OnClose public void onClose() { System.out.println("Connection closed"); } // Method called by transmission message error @OnError public void OnError(Throwable error) { System.out.println("Connection error"); } }
4. Front end code
<!DOCTYPE html> <html> <head> <title>Testing websockets</title> </head> <body> <div> <textarea rows="3" cols="20" id="content"></textarea> <br> <input type="submit" value="Start" onclick="start()" /> </div> <div id="messages"></div> <script type="text/javascript"> var webSocket = new WebSocket('ws://localhost:8080/websocket'); webSocket.onerror = function(event) { onError(event) }; webSocket.onopen = function(event) { onOpen(event) }; webSocket.onmessage = function(event) { onMessage(event) }; webSocket.onclose = function(event) { onClose(event) }; function onMessage(event) { document.getElementById('messages').innerHTML += '<br />' + event.data; } function onOpen(event) { document.getElementById('messages').innerHTML = 'Connection established'; } function onError(event) { alert(event); } function onClose(event) { alert(event); } function start() { var text = document.getElementById('content').value; webSocket.send(text); } </script> </body> </html>
So you can see that websocket is very simple, just write 4 event methods at the front and back (of course, you can also omit some methods)
1. Establish a connection 2. Message received 3. Failed to transmit message 4. Close the connection
Event and session specific association
If an event wants to be associated with a specific Session, only the Session parameter is added to the method (it can be added to the methods of four event types)
For example, send the user directly to the server and then return it to the client
// Method called by received message @OnMessage public void onMessage(Session session, String message) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } }
Transfer parameters
Add @ PathParam parameter to the method
@Component @ServerEndpoint("/websocket/{sid}") public class WebSocketServerController
@OnOpen public void onOpen(@PathParam("sid") String sid) { System.out.println("Client connected"); }
Realize an online group chat
Back-end interface
@Slf4j @Component @ServerEndpoint("/groupChat/{sid}/{username}") public class GroupChatController { // Save the mapping relationship of group ID - > group members private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap<>(); // Method called by receiving message, group member sends message @OnMessage public void onMessage(@PathParam("sid") String sid, @PathParam("username") String username, String message) { List<Session> sessionList = groupMemberInfoMap.get(sid); // Send messages to members of a group first sessionList.forEach(item -> { try { String text = username + ": " + message; item.getBasicRemote().sendText(text); } catch (IOException e) { e.printStackTrace(); } }); } // Set up the method of connection call, group members join @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { List<Session> sessionList = groupMemberInfoMap.get(sid); if (sessionList == null) { sessionList = new ArrayList<>(); groupMemberInfoMap.put(sid,sessionList); } sessionList.add(session); log.info("Connection connected"); log.info("sid: {}, sessionList size: {}", sid, sessionList.size()); } // Close method called by connection, group member exits @OnClose public void onClose(Session session, @PathParam("sid") String sid) { List<Session> sessionList = groupMemberInfoMap.get(sid); sessionList.remove(session); log.info("Connection closed"); log.info("sid: {}, sessionList size: {}", sid, sessionList.size()); } // Method called by transmission message error @OnError public void OnError(Throwable error) { log.info("Connection error"); } }
The front-end code is very simple, put github The address is: https://github.com/erlieStar/spring-boot-websocket
Let's see the effect Pay attention to connecting before sending Online address: http://www.javashitang.com:8090/
Welcome to your attention.
Reference blog
Good essay [1]https://blog.csdn.net/moshowgame/article/details/80275084 [2]https://www.jianshu.com/p/d79bf8174196 [3]https://www.byteslounge.com/tutorials/java-ee-html5-websocket-example A group chat program [4]https://blog.csdn.net/moshowgame/article/details/80275084