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

What is the development process of SpringBoot and WebSocket?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

SpringBoot and WebSocket development process is how, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

1. I have tried two ways to implement the server side:

The first is implemented with "@ ServerEndPoint" annotations, which are simple to implement.

The second is a bit cumbersome, but you can add interceptors to do some extra work before the WebSocket connection is established and disconnected.

No matter which implementation method is used, you need to import the jar package first (as follows), where version is selected according to the actual springboot version to avoid conflicts.

Org.springframework.boot spring-boot-starter-websocket

1.1 the first implementation method

(1) implementation of WebSocket business logic. The parameter is passed by the method of path parameter, and the parameter is obtained in the following ways:

@ ServerEndpoint ("/ testWebSocket/ {id} / {name}")

Public void onOpen (Session session, @ PathParam ("id") long id, @ PathParam ("name") String name)

Import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RestController;@ServerEndpoint ("/ testWebSocket/ {id} / {name}") @ RestControllerpublic class TestWebSocket {/ / variable used to record the current number of connections private static volatile int onlineCount = 0 / / Thread-safe Set of the concurrent package, which is used to store the MyWebSocket object private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet () corresponding to each client; / / the connection session with a client needs to be used to send and receive private Session session; private static final Logger LOGGER = LoggerFactory.getLogger (TestWebSocket.class) to the client. @ OnOpen public void onOpen (Session session, @ PathParam ("id") long id, @ PathParam ("name") String name) throws Exception {this.session = session; System.out.println (this.session.getId ()); webSocketSet.add (this); LOGGER.info ("Open a websocket. Id= {}, name= {} ", id, name);} @ OnClose public void onClose () {webSocketSet.remove (this); LOGGER.info (" Close a websocket. "); @ OnMessage public void onMessage (String message, Session session) {LOGGER.info (" Receive a message from client: "+ message);} @ OnError public void onError (Session session, Throwable error) {LOGGER.error (" Error while websocket. , error);} public void sendMessage (String message) throws Exception {if (this.session.isOpen ()) {this.session.getBasicRemote (). SendText ("Send a message from server. Public static synchronized int getOnlineCount () {return onlineCount;} public static synchronized void addOnlineCount () {TestWebSocket.onlineCount++;} public static synchronized void subOnlineCount () {TestWebSocket.onlineCount--;}}

(2) configure ServerEndpointExporter. After configuration, all Websocket Endpoint declared by "@ ServerEndpoint" annotation will be automatically registered.

Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter; @ Configurationpublic class WebSocketConfig {@ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();}}

1.2 the second implementation method

(1) implementation of WebSocket business logic. Parameters are passed in a way similar to GET requests, and the server-side parameters are obtained in the interceptor and passed to WebSocketHandler through attributes.

Import java.util.ArrayList;import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.WebSocketMessage;import org.springframework.web.socket.WebSocketSession; @ RestControllerpublic class TestWebSocketController implements WebSocketHandler {private static AtomicInteger onlineCount = new AtomicInteger (0); private static final ArrayList sessions = new ArrayList () Private final Logger LOGGER = LoggerFactory.getLogger (TestWebSocketController.class); @ Override public void afterConnectionEstablished (WebSocketSession session) throws Exception {sessions.add (session); int onlineNum = addOnlineCount (); LOGGER.info ("Oprn a WebSocket. Current connection number: "+ onlineNum);} @ Override public void afterConnectionClosed (WebSocketSession session, CloseStatus status) throws Exception {sessions.remove (session); int onlineNum = subOnlineCount (); LOGGER.info (" Close a webSocket. Current connection number: "+ onlineNum);} @ Override public void handleMessage (WebSocketSession wsSession, WebSocketMessage message) throws Exception {LOGGER.info (" Receive a message from client: "+ message.toString ());} @ Override public void handleTransportError (WebSocketSession session, Throwable exception) throws Exception {LOGGER.error (" Exception occurs on webSocket connection. Disconnecting.... "); if (session.isOpen ()) {session.close ();} sessions.remove (session); subOnlineCount ();} / * * whether message splitting is supported: if the amount of data received is relatively large, it is best to open it (true), otherwise it may cause reception failure. * if the WebSocket connection is automatically disconnected after receiving data once, check to see if this is the problem. * / @ Override public boolean supportsPartialMessages () {return true;} public static int getOnlineCount () {return onlineCount.get ();} public static int addOnlineCount () {return onlineCount.incrementAndGet ();} public static int subOnlineCount () {return onlineCount.decrementAndGet ();}}

(2) implementation of HandShake interceptor

Import java.util.Map; import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.http.server.ServletServerHttpRequest;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; public class TestHandShakeInterceptor extends HttpSessionHandshakeInterceptor {private final Logger LOGGER = LoggerFactory.getLogger (TestHandShakeInterceptor.class) / * * before the WebSocket connection is established, take authentication as an example * / @ Override public boolean beforeHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {LOGGER.info ("Handle before webSocket connected. "); / / get the parameters passed by url, which can be passed to WebSocketHandler / / WebSocketHandler through attributes after Interceptor processing. You can get the parameters ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request; String id = serverRequest.getServletRequest (). GetParameter (" id "); String name = serverRequest.getServletRequest (). GetParameter (" name ") through the getAttributes () method of WebSocketSession. If (tokenValidation.validateSign ()) {LOGGER.info ("Validation passed. WebSocket connecting.... Attributes.put ("id", id); attributes.put ("name", name); return super.beforeHandshake (request, response, wsHandler, attributes);} else {LOGGER.error ("Validation failed. WebSocket will not connect. "); return false;} @ Override public void afterHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {/ / omitted}}

(3) WebSocket configuration class implementation (registers the WebSocket implementation class, binds the interface, and binds the implementation class with the interceptor)

Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import TestWebSocketController;import TestHandShakeInterceptor; @ Configuration@EnableWebMvc@EnableWebSocketpublic class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {@ Autowired private TestWebSocketController testWebSocketController @ Override public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {registry.addHandler (TestWebSocketController, "/ testWebSocket") .addInterceptors (new TestHandShakeInterceptor ()) .setAllowedOrigins ("*");}}

1.3 additional notes

(1) during the implementation of WebSocket, especially through "@ ServerEndpoint", the problem of injection failure may occur, that is, the injected Bean is null. You can solve this problem by manual injection. You need to modify the implementation class and SpringBoot startup class, as shown below:

ServerEndpoint ("testWebsocket") @ RestControllerpublic class WebSocketController {private TestService testService; private static ApplicationContext applicationContext; @ OnOpen public void onOpen (Session session) {testService = applicationContext.getBean (TestService.class);} @ OnClose public void onClose () {} @ OnMessage public void onMessage (String message, Session session) {} @ OnError public void onError (Session session, Throwable error) {} public static void setApplicationContext (ApplicationContext applicationContext) {WebSocketController.applicationContext = applicationContext }} import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext; import WebSocketController; @ SpringBootApplicationpublic class Application {public static void main (String [] args) {/ / SpringApplication.run (Application.class, args); SpringApplication springApplication = new SpringApplication (Application.class); ConfigurableApplicationContext configurableApplicationContext = springApplication.run (args); WebSocketController.setApplicationContext (configurableApplicationContext) / / solve the problem that WebSocket cannot be injected}}

two。 For the implementation of the client, I have tried html and java WebSocketClient.

2.1 html implementation

WebSocket example closes WebSocket connection var websocket = null; / / determines whether the current browser supports WebSocket if ('WebSocket' in window) {/ / write websocket = new WebSocket ("ws://127.0.0.1:18080/testWebsocket") without parameters / / the method of passing parameters through the path (the server uses the first method "@ ServerEndpoint") websocket = new WebSocket ("ws://127.0.0.1:18080/testWebsocket/23/Lebron") / / pass parameters through a method similar to GET request (the server uses the second method "WebSocketHandler" to implement) websocket = new WebSocket ("ws://127.0.0.1:18080/testWebsocket?id=23&name=Lebron") } else {alert ('current browser Not support websocket')} / / callback method of connection error websocket.onerror = function () {setMessageInnerHTML ("WebSocket connection error occurred");}; / / callback method websocket.onopen = function () {setMessageInnerHTML ("WebSocket connection success") } / / callback method websocket.onmessage = function (event) {setMessageInnerHTML (event.data);} / / callback method websocket.onclose = function () {setMessageInnerHTML ("WebSocket connection 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 () {closeWebSocket ();} / / display the message on the web page function setMessageInnerHTML (innerHTML) {document.getElementById ('message') [xss_clean] + = innerHTML +';} / / close the WebSocket connection function closeWebSocket () {websocket.close () } / / send the message function send () {var message = document.getElementById ('text'). Value; websocket.send (message);}

2.2 Java WebSocketClient implementation

(1) WebSocketClient implementation class

Import java.net.URI; import org.java_websocket.client.WebSocketClient;import org.java_websocket.drafts.Draft;import org.java_websocket.handshake.ServerHandshake;import org.slf4j.Logger;import org.slf4j.LoggerFactory; public class TestWebSocketClient extends WebSocketClient {private final Logger LOGGER = LoggerFactory.getLogger (TestWebSocketClient.class); public TestWebSocketClient (URI serverUri) {super (serverUri);} public TestWebSocketClient (URI serverUri, Draft protocolDraft) {super (serverUri, protocolDraft) } @ Override public void onOpen (ServerHandshake serverHandshake) {LOGGER.info ("Open a WebSocket connection on client. @ Override public void onClose (int arg0, String arg1, boolean arg2) {LOGGER.info ("Close a WebSocket connection on client. ");} @ Override public void onMessage (String msg) {LOGGER.info (" WebSocketClient receives a message: "+ msg);} @ Override public void onError (Exception exception) {LOGGER.error (" WebSocketClient exception. ", exception);}}

(2) WebSocketClient sends data

String serverUrl = "ws://127.0.0.1:18080/testWebsocket" URI recognizeUri = new URI (serverUrl); client = new TestWebSocketClient (recognizeUri, new Draft_6455 ()); client.connect (); client.send ("This is a message from client."); is it helpful for you to finish reading the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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