Spring boot and WebSocket
1. Broadcast type
1. Use @enablewebsocketmessagebroker to turn on WebSocket support in the configuration class.
Stompendpointregistry.addendpoint ("/endpointwisely"). Withsocketjs (); Registering the node for the STOMP protocol, configuring the developed URL
Stompendpointregistry.enablesimplebroker ("/topic"); Configure the message agent and also the URL prefix of the server-side Send Message
2. In the controller
@Controller
public class wscontroller{
@MessageMapping ("/hello")//Browser request path
@SendTo ("/topic/getresponse")
Public wiselyresponse Say (Wiselymessage message) {
return new Wiselyresponse ("Hello" +message);
}
3. In the page JS
var socket = new Sockjs ('/endpointwisely '); //The node URL configured in config
Stompclient.subscribe ('/topic/getresponse ')//subscription, browser-and server, corresponding to the path of @sendto annotations in the controller
Stompclient.send ('/hello ')//Send message, server-to-browser, corresponding to the path of @messagemapping annotations in the controller
2. Point-to-point
Simpmessagingtemplate is a spring-websocket built-in message sending tool that can send messages to the specified client.
@Controller
public class wscontroller{
@Autowired
Private Simpmessagingtemplate simpmessagingtemplate;
@MessageMapping ("/point2p")//Browser request path
public void Say (String message) {
Simpmessagingtemplate.convertandsendtouser ("User receiving message", "/topic/getresponse", message);
}
}
And JS in the path Stompclient.subscribe ('/user/topic/getresponse '), more than one/user, indicating the sending of messages to the specified user.
Spring Boot (ii) websocket