Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement WebSocket chat room with single thread and scheduled task respectively

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use single-threaded and scheduled tasks to achieve WebSocket chat room". The content of the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn "how to use single-threaded and scheduled tasks to achieve WebSocket chat room".

1. Demand scenario

Multimedia real-time chat

Quotation of data such as stock fund

Position positioning

Social subscription

Database update, front-end real-time display

In order to realize this real-time function, polling and Comet technology are often used in the past.

Polling: the client is required to periodically send requests to the server at the set time interval, frequently querying whether the data has changed. Disadvantages: too many unnecessary requests, waste of traffic and server resources. Comet technology: can be divided into long polling and streaming technology. Long polling improves the above polling, reduces useless requests, sets the expiration time, and sends requests to the server only after the data expires, which is suitable for scenarios where data changes are infrequent. Streaming technology means that the client establishes a HTTP persistent connection with the server through a hidden window and constantly updates the connection status to keep the connection open.

Summary: it is all based on the request-response mode, which is not a real-time technology in the real sense. Every request and reply consumes a certain amount of traffic.

2.WebSocket principle

The WebSocket protocol is implemented based on the TCP protocol, and the workflow is like this: the browser sends a request to the server to establish a WebSocket connection through JavaScript. After the WebSocket connection is established, the client and the server can transmit data through the TCP connection. Because WebSocket connections are essentially TCP connections, there is no need to bring duplicate header data with each transmission, and its advantages:

After the first connection is established through the first Http Request, the subsequent data exchange does not resend the Http Request, thus saving broadband resources.

WebSocket protocol is a two-way communication protocol, which can be sent and accepted.

Multiplexing means that multiple different URL can reuse the same Websocket connection

3. Create a warm reminder for Websocket chat rooms: based on IAEA+SpringBoot+Gradle development, thanks to the automatic configuration provided by SpringBoot, you can create a WebSocket server through a simple annotation @ ServerEndpoint, and then complete the writing of a WebSocket server through a simple callback function!

Build.gadle

/ / spring-boot-starter-websocket 's springboot-dependent advanced components automatically reference the underlying components / for example, spring-boot-starter-websocket introduces spring-boot-starter-web and spring-boot-starter compile group: 'org.springframework.boot', name:' spring-boot-starter-websocket', version: '2.1.6.RELEASE' / / thymeleaf compile group: 'org.springframework.boot', name:' spring-boot-starter-thymeleaf', version: '2.1.6.RELEASE.'

Create a WebSocketConfig

Package com.example.SmartHome.config;import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;import org.springframework.web.socket.server.standard.ServerEndpointExporter / * * @ Description: Websocket endpoint * @ ClassName: WebSocketConfig * @ Author: zzq * @ Date: 11:01 on 2019-7-7 * @ Version: / @ Configuration@Component@ConditionalOnWebApplicationpublic class WebSocketConfig {/ * Auto-registration uses the Websocket endpoint * / @ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter () of @ ServerEndpoint annotation statement }} reminder: ServerEndpointExporter is a standard implementation officially provided by Spring, which is used to scan ServerEndpointConfig configuration classes and @ ServerEndpoint annotation instances. Rules of use: 1. If you use a default embedded container such as Tomcat, you must manually provide ServerEndpointExporter in the context. two。 If you deploy the war package using an external container, do not provide the ServerEndpointExporter, because SpringBoot defaults to handing over the behavior of the scanning server to the external container.

Create a WebSocket server

Core idea: ① declares the instantiated WebSocket server by annotating @ ServerEndpoint. ② declares the callback function by annotating @ OnOpen, @ OnMessage, @ OnClose, @ OnError. Event type annotation event description open@OnOpen triggers message@OnMessage when opening a connection, triggers error@OnError when receiving client messages, triggers close@OnClose when communication is abnormal, triggers package com.example.SmartHome.server;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet when connection closes / * * @ Description: WebSocketServer server * @ ClassName: WebSocketServer * @ Author: zzq * @ Date: 2019-7-3 17:05 * @ Version: 1.0 * / / ServerEndpoint this bean will automatically register Websocket endpoint that uses the @ ServerEndpoint annotation declaration. Note that if you use a separate servlet container instead of directly using springboot's built-in container, / / do not inject ServerEndpointExporter,// because it will be provided and managed by the container itself. / * * @ ServerEndpoint annotation is a class-level annotation Its main function is to define the current class as a websocket server, and the value of the * note will be used to listen for the terminal access URL address of the user connection. The client can connect to the WebSocket server through this URL * / @ ServerEndpoint ("/ websocket") @ Component / / its main function is to integrate the listener into the Spring container to manage public class WebSocket {/ / MyThread thread1=new MyThread (). / / Thread thread = new Thread (thread1); / / each client will have a corresponding session. The server can send the relevant message private Session session; public static int onlineCount = 0; / / the thread-safe class under the J.U.C package is mainly used to store the webSocket connection private static CopyOnWriteArraySet copyOnWriteArraySet = new CopyOnWriteArraySet () for each client; / * * @ Name:onOpen * @ Description: open the connection. When you enter the page, you will automatically send a request to connect here * / @ OnOpen public void onOpen (Session session) throws IOException {this.session = session; copyOnWriteArraySet.add (this); addOnlineCount (); System.out.println ("websocket has new connections, total: + getOnlineCount ()); sendMessage (" successful connection ") } / * * @ Name:onClose * @ Description: the user closes the page, that is, closes the connection * / @ OnClose public void onClose () {copyOnWriteArraySet.remove (this); shortOnlineCount (); System.out.println ("websocket connection disconnected, total:" + getOnlineCount ()) } / * * @ Name:onMessage * @ Description: method called after receiving the client message * / @ OnMessage public void onMessage (String message,Session session) throws IOException {System.out.println ("websocket receives the message from the client:" + message); for (WebSocket webSocket:copyOnWriteArraySet) {webSocket.sendMessage (message) }} / * * @ Name:onError * @ Description: error * / @ OnError public void onError (Session session, Throwable error) {System.out.println ("error occurs:" + error.getMessage () + "; sessionId:" + session.getId ()); error.printStackTrace () } public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message); / / this.session.getAsyncRemote () .sendText (message);} public void sendMessage (Object object) {/ / traversal client for (WebSocket webSocket: copyOnWriteArraySet) {System.out.println ("websocket broadcast message:" + object.toString ()) Try {/ / the server actively pushes webSocket.session.getBasicRemote () .sendObject (object);} catch (Exception e) {e.printStackTrace () } / * * @ Name:sendMessage * @ Description: used to send messages to clients (mass) * / public static void sendInfo (String message) {/ / traverse client for (WebSocket webSocket: copyOnWriteArraySet) {System.out.println ("websocket broadcast messages:" + message) Try {/ / the server actively pushes webSocket.session.getBasicRemote () .sendText (message);} catch (Exception e) {e.printStackTrace () } / * * @ Name:sendMessage * @ Description: used to send a message to the specified client * / public void sendMessage (String sessionId, String message) throws IOException {Session session = null; WebSocket tempWebSocket = null For (WebSocket webSocket: copyOnWriteArraySet) {if (webSocket.session.getId () .equals (sessionId)) {tempWebSocket = webSocket; session = webSocket.session; break;}} if (session! = null) {tempWebSocket.session.getBasicRemote () .sendText (message) } else {System.out.println ("did not find the session you specified ID: {}" + "; sessionId:" + sessionId);}} public static synchronized int getOnlineCount () {return onlineCount;} public static synchronized void addOnlineCount () {WebSocket.onlineCount++;} public static synchronized void shortOnlineCount () {WebSocket.onlineCount--;}}

4.Controller class package com.example.SmartHome.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/* * @ Description: TODO * @ ClassName: ChatController * @ Author: zzq * @ Date: 16:56 * @ Version: 2019-7-9 * / @ Controllerpublic class ChatController {@ RequestMapping ("/ websocket") public String init () {return "websocket.html";}} 5. The front-end code My WebSocket Test Welcome Close var websocket = null; / / determines whether the current browser supports WebSocket if ('WebSocket' in window) {websocket = new WebSocket ("ws:2559qs1996.qicp.vip:20422/websocket");} else {alert (' Not support websocket')} / / callback method websocket.onerror = function () {setMessageInnerHTML ("error");} / / callback method websocket.onopen = function (event) {setMessageInnerHTML ("open");} / / callback method websocket.onmessage = function (event) {setMessageInnerHTML (event.data);} / / callback method websocket.onclose = function () {setMessageInnerHTML ("close") when the connection is closed } / / listen for the window closing event. When the window closes, it takes the initiative to close the websocket connection to prevent the window from being closed before the connection is disconnected. An exception will be thrown on the server side. _ window.onbeforeunload = function () {websocket.close ();} / display the message on the web page function setMessageInnerHTML (innerHTML) {document.getElementById ('message') [xss_clean] + = innerHTML +';} / close the connection function closeWebSocket () {websocket.close ();} / / send the message function send () {var message = document.getElementById ('text'). Value Websocket.send (message);}

6. Result display

Server:

Thank you for your reading, the above is the content of "how to use single-threaded and scheduled tasks to achieve WebSocket chat rooms respectively". After the study of this article, I believe you have a deeper understanding of how to use single-threaded and scheduled tasks to achieve WebSocket chat rooms, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report