This article was reproduced from: http://www.jianshu.com/p/60799f1356c5
WebSocket is a major feature of HTML5, making it possible to interact with real long-connected browsers and services, and this article will lead you to a glimpse of spring's support and use of websocket.
1. Basic Environment
To quickly build the spring framework, we use Spring boot, which does not discuss springboot, only that it is a "one-stop solution for quick-build spring Projects".
To use spring's websocket feature, we need to add dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId></dependency>
This makes it easy to open the WebSocket basic functionality.
2. Related configurations
Let's configure WebSocket.
First add a Websocketconfig class that defines the global configuration information, using the form of Javaconfig:
Websocketconfig.java
@Configuration@EnableWebSocketMessageBrokerPublicClasswebsocketconfig extends abstractwebsocketmessagebrokerconfigurer { @Override public void registerstompendpoints "/socket"). Withsockjs (); } @Override public void configuremessagebroker ( Messagebrokerregistry registry) {Registry.enablesimplebroker ( "/topic"); Registry.setapplicationdestinationprefixes ( "/app");}
Related instructions:
registerStompEndpoints(StompEndpointRegistry registry)
The function of this method is to add a service endpoint to receive the client's connection.
registry.addEndpoint("/socket")
Indicates that an endpoint is added /socket
and the client can connect through the endpoint.
withSockJS()
The role of SOCKJS is to turn on support,
configureMessageBroker(MessageBrokerRegistry config)
The function of this method is to define the message agent, in layman's words, to set up the message connection request of the various specifications information.
registry.enableSimpleBroker("/topic")
The prefix information that represents the client's subscription address, which is the prefix information for the client to receive the address of the server-side message (compare around, read the entire example, probably will understand)
registry.setApplicationDestinationPrefixes("/app")
Refers to the prefix of the server's receiving address, meaning the prefix of the address that the client sends the message to the service side
The information defined in the above two methods is actually the opposite, one defines the address prefix that the client receives, and a prefix that defines the client's sending address
So far, the entire framework of configuration information has been completed, let's write an example to send an announcement, to show the charm of WebSocket!
3. Writing background business
With the basic configuration information described above, we can write basic functions. Here is a brief explanation of two points of knowledge:
- Messagemapping
Spring is particularly simple for the WebSocket package, providing an @MessageMapping
annotation that is similar @RequestMapping
in function, that it exists in Controller
, defines a basic request for a message, and functions @RequestMapping
like a URL definition that supports wildcard characters, etc. For detailed usage See annotation Message handling
- Simpmessagingtemplate
SimpMessagingTemplate
is a spring-websocket built-in message sending tool that can send messages to the specified client.
Let's implement:
Create a new one GreetingController
,
@ControllerPublicClassgreetingcontroller { @Resource Private Simpmessagingtemplate simpmessagingtemplate; @RequestMapping ( "/hellosocket") < Span class= "Hljs-keyword" >public String index () {return "/hello/index ";} @MessageMapping ( "/change-notice") public void greeting (String value) { This.simpMessagingTemplate.convertAndSend ( "/topic/notice", Value);}}
Related instructions:
- Index ()
Specifies a page to implement the WebSocket client to send the announcement function, using @RequestMapping
, therefore receives the HTTP request, carries on the page to jump.
- Greeting (String value)
This method is to receive the WebSocket request that the client sends the power announcement, using the @MessageMapping
.
this.simpMessagingTemplate.convertAndSend("/topic/notice", value)
The official explanation for this method is Convert the given Object to serialized form, possibly using a MessageConverter, wrap it as a message and send it to the given destination.
"to serialize a given object, use ' messageconverter ' to wrap it into a message, send it to the specified target," and the popular point is that we use this method to send messages forward!
Before we specified in the global configuration that the server received the connection with a large app
head, the client sends the request connection for the announcement should be /app/change-notice
.
The server-side code is so simple, similar to writing SPRINGMVC, and the same geeting(String value)
way we can use another annotation for @SendTo
another notation.
@MessageMapping("/change-notice")@SendTo("/topic/notice")public String greeting(String value) { return value;}
Related instructions:
The improved code is simpler and more focused on understanding @SendTo
.
@SendTo
Defines the destination of the message. An example of this is "receive /app/change-notice
the value sent, and then forward the value to the /topic/notice
client."
/topic/notice
is an address that is specified when the client initiates a connection, subscribes to the server's message, and is used to receive the return of the server, which we will see when we write the client code.
So far, the service-side code coding finished! Next article we will write the client function.
Spring WebSocket Introduction (i) reprint