WebSocket Introduction
WebSocket protocol is a kind of network protocol based on TCP. It enables full duplex communication between the browser and the server--allowing the server to actively send information to the client.
WebSocket is a socket to achieve duplex asynchronous communication. It is particularly cumbersome to use WebSocket or SOCKJS protocols directly. Using its sub-protocol stomp, it is a higher level protocol, STMOP protocol uses a frame-based format to define messages, similar to HTTP's request and response.
Springboot to the use of WebSocket provided support, configuration source code in the Org.springframework.boot.autoconfigure.websocket package.
Maven dependencies used in the case:
<!--springboot Other dependencies ellipsis-->
<!--webSocket-->
<dependency>
<groupId> Org.springframework.boot</groupid>
<artifactid>spring-boot-starter-websocket</artifactid >
</dependency>
<!--thymeleaf template engine-->
<dependency>
<groupId> Org.springframework.boot</groupid>
<artifactid>spring-boot-starter-thymeleaf</artifactid >
</dependency>
<!--spring security-->
<dependency>
<groupId> Org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid >
</dependency>
Broadcast Mode
When a message is broadcast on the server, the message is sent to all browsers connected to the current endpoint.
1, write Message class
/**
* The message sent by the browser to the server
/public class Aricmessage {
private String name;
Public String GetName () {return
name;
}
}
/**
* Server-side message sent to the browser * * Public
class Aricresponse {
private String responsemessage;
Public Aricresponse (String responsemessage) {
this.responsemessage = responsemessage;
}
Public String Getresponsemessage () {return
responsemessage
}}
2. Configure WebSocket
/**
* Configure WebSocket
/@Configuration
//annotations to enable the use of the Stomp Protocol to transport agent-based (message broker) messages, The controller supports the use of @messagemapping, just like using @requestmapping
@EnableWebSocketMessageBroker public
class Websocketconfig extends abstractwebsocketmessagebrokerconfigurer{
@Override public
Void Registerstompendpoints (Stompendpointregistry Registry) {//Register STOMP Protocol node (endpoint) and map the specified URL
// Registers a STOMP endpoint and specifies the use of the SOCKJS protocol
registry.addendpoint ("/endpointaric"). WITHSOCKJS ()
;
@Override public
void Configuremessagebroker (Messagebrokerregistry registry) {//Configure message Broker
// Broadcast should be configured with a/TOPIC message agent
registry.enablesimplebroker ("/topic");
}
3, write Controller
/**
* WebSocket Controller
*
/@Controller public
class Websocketcontroller {
@MessageMapping ("/welcome ")///When the browser sends a request to the server,/welcome this address via @messagemapping mapping, similar to @responsemapping
@SendTo ("/topic/getresponse ")/ When the server has a message, a message is sent to the browser that subscribes to the path in @sendto public
aricresponse say (aricmessage messages) {
try {
//sleep 1 seconds
Thread.Sleep (1000);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
return new Aricresponse ("Welcome," + message.getname () + "!");
}
4, in the Src\main\resource\templates directory to write websocket.html, using the Thymeleaf template engine
<!
DOCTYPE html>
5, configure Viewcontroller, provide path mapping for websocket.html.
/**
* Configure Viewcontroller to provide path mapping for the page *
*
@Controller public
class Webmvcconfig extends webmvcconfigureradapter{
/**
* Configuration Viewcontroller, providing mapping path
/
@Override public
Void Addviewcontrollers (Viewcontrollerregistry registry) {
Registry.addviewcontroller ("/websocket"). SetViewName ( "/websocket");
}
6, open multiple browsers, access to the address, one of the sending messages, other browsers can receive messages. point to Point type
The point-to-point approach solves the problem of who sent the message and who receives it.
Use the spring security, simple configuration.
/** * Spring Security Configuration */@Configuration @EnableWebSecurity public class Websecurityconfig extends Websecurityconfigure radapter{@Override protected void Configure (Httpsecurity http) throws Exception {http.authorizerequests (). Antmatchers ("/", "Login"). Permitall ()//Set Spring security pair/and/login path does not intercept. Anyrequest (). Authen Ticated (). and (). Formlogin (). LoginPage ("/login")/Set the landing page access path for spring security to login. defaultsuccess
URL ("/chat")//login succeeded to the/chat path. Permitall (). and (). Logout (). Permitall (); @Override protected void Configure (Authenticationmanagerbuilder auth) throws Exception {//Configure two users, role is US
Er auth.inmemoryauthentication (). Withuser ("James"). Password ("James"). Roles ("User"). and ()
. Withuser ("Curry"). Password ("Curry"). Roles ("User"); @Override public void Configure (Websecurity Web) throws Exception {//Set SpringSecutiry does not intercept static resources in the/resources/static/directory Web.ignoring (). Antmatchers ("/resources/static/**");
}
}
Configure WebSocket
/**
* Configure WebSocket
/@Configuration
//annotations to enable the use of the Stomp Protocol to transport agent-based (message broker) messages, The controller supports the use of @messagemapping, just like using @requestmapping
@EnableWebSocketMessageBroker public
class Websocketconfig extends abstractwebsocketmessagebrokerconfigurer{
@Override public
Void Registerstompendpoints (Stompendpointregistry Registry) {//Register STOMP Protocol node (endpoint) and map the specified URL
// Registers a STOMP endpoint and specifies the use of the SOCKJS protocol
registry.addendpoint ("/endpointaric"). WITHSOCKJS ();
Registers the endpoint
registry.addendpoint ("/endpointchat") named "Endpointchat". Withsockjs ();
@Override public
void Configuremessagebroker (Messagebrokerregistry registry) {//Configure message Broker
// Broadcast type should be configured with a/TOPIC message agent
// Registry.enablesimplebroker ("/topic");
Point-to-Point should configure the/queue and/topic message agent
registry.enablesimplebroker ("/queue", "/topic");
}
Write Controller
/** * WebSocket Controller/@Controller public class Websocketcontroller {//Send messages to the browser via Simpmessagingtemplate @Autowir
Ed private Simpmessagingtemplate simpmessagingtemplate; @MessageMapping ("/chat")//In Springmvc, you can get the principal,pinciple containing the current user information in the argument directly in the parameters public void Handlechat (Principal prin Cipal,string msg) {if ("James". Equals (Principal.getname ())) {//hard-coded, to judge the user's name///Send a message to the user, first parameter: the user receiving the message, Two parameters: Browser subscription address, third parameter: Message simpmessagingtemplate.convertandsendtouser ("Curry", "/queue/notific
Ations ", Principal.getname () +"-send: "+ msg); else {simpmessagingtemplate.convertandsendtouser ("James", "/queue/notifications", Prin
Cipal.getname () + "-send:" + msg); } @MessageMapping ("/welcome")//when the browser sends a request to the server,/welcome this address through @messagemapping mapping, similar to the @responsemapping @SendTo (" /topic/getresponse ")////When the server has a message, it sends a message to the browser that subscribes to the path in @sendto public aricresponse say (Aricmessage messagE) {try {//Sleep 3 seconds thread.sleep (3000);
catch (Interruptedexception e) {e.printstacktrace ();
Return to New Aricresponse ("Welcome," + message.getname () + "!");
}
}
Write login.html and chat.html in the Src\main\resource\templates directory
<! DOCTYPE html>
Chat page
<! DOCTYPE html>
Configure Viewcontroller
/**
* Configure Viewcontroller to provide path mapping for the page *
*
@Controller public
class Webmvcconfig extends webmvcconfigureradapter{
/**
* Configuration Viewcontroller, providing mapping path
/
@Override public
Void Addviewcontrollers (Viewcontrollerregistry registry) {
Registry.addviewcontroller ("/websocket"). SetViewName (" /websocket ");
Registry.addviewcontroller ("/login"). Setviewname ("/login");
Registry.addviewcontroller ("/chat"). Setviewname ("/chat");
}
Open the browser to achieve point-to-point chat