Go straight:
The web projects are generally short connection, the initiative is handed over to the hands of the client, in case the client does not send the request, the server is no way to take the initiative to send a message to the client. But in some cases, we need a long connection, such as common to the chat room. Online there are many cases there is not much to say! ()
java rear end portion
First of all, we need to import maven node
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
Traditional games are played, you need to configure a class WebSocketConfiguration, he needs to realize WebSocketMessageBrokerConfigurer. Override the two methods configureMessageBroker, registerStompEndpoints
package com.lhf.novel.config.socket; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; /** * WebSocketConfigufation实体类 * * @author zy * @since 2020/3/20$ */ @Configuration @EnableWebSocketMessageBroker // @Deprecated public class WebSocketConfiguration the implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker (MessageBrokerRegistry Registry) { registry.enableSimpleBroker ( "/ Topic" ); // register a queue message mainly used for distinguishing (in my opinion) } @override public void registerStompEndpoints (StompEndpointRegistry Registry) { registry.addEndpoint ( "/api").setAllowedOrigins("*" ) .addInterceptors () withSockJS ();. @ straightaway simple terms, addEndpoint ( "/ API ") is the time client connections url address, behind not explained. . .
} }
The client will connect.
Now add a test, take the initiative to push messages to the client ********
package com.lhf.novel.config.socket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * MessageService实体类 * * @author zy * @since 2020/3/22 */ @Component public class MessageService { @Autowired private SimpMessagingTemplate messagingTemplate; @Scheduled(fixedDelay = 5000) // spring of scheduled tasks, represented here performed once every five seconds, you need to add a comment on the @ configuration class or starting class EnableScheduling, so to take effect
public void mes() { messagingTemplate.convertAndSend("/topic","125"); } }
Here SimpMessagingTemplate a message template is built, as used herein, his convertAndSend () method, the first parameter is transmitted to the channel, the second parameter is the content transmission thus can connect the client.
vue distal portion
First need to import two dependencies
npm install socket-client
npm install stompjs
import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { name: "Index", data() { return { socket: null, stompClient: null, name: 'admin', mes: '', cmes: '', } }, mounted() { this.init(); }, destroyed() { the this .stompClient.destroyed (); }, Methods: { the init () { the let _that = the this ;
// connected Socket the this .socket = new new SockJS ( 'HTTP: // localhost: 8080 / API' ); the let stompClient = Stomp .over ( the this .socket); stompClient.connect ({ Login: 'ADMIN' , PassCode: '123456' }, function (Frame) { window.console.log (Frame)
// subscription, subscription service where the registered terminal topic stompClient.subscribe ( '/ Topic' , function (Message) { window.console.warn (Message); _that.cmes = message.body // window.console.log (the JSON.parse (message.body)); }) ; }) the this .stompClient = stompClient; }, send () {
// this message is sent the this .stompClient.send ( "/ MES", {}, "message sent by the client" ) } } }
So that the front end is almost completed
Open developer mode F12 can see, every five seconds the server will push a message over.
These are the server sends a message, chat window must be multi-point or multi-point mode is, then you need to have the concept of a user, which is the need to add springsecurity.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
security configuration partially omitted. . . I have two users configured with the root and admin
This requires a controller
package com.lhf.novel.config.socket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; /** * TestController实体类 * * @author zy * @since 2020/3/22 */ @RestController public class TestController { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/mes") //@SendTo("/topic") public void mes(Principal principal, String mess) { System.out.println("name:"+principal.getName()); System.out.println("mes = " + mess); messagingTemplate.convertAndSendToUser("admin","/topic","我来了"); // return principal.getName()+":发来致电"; } }
@MessageMapping and RequestMapping effect is the same, the path setting request
@SendTo return passage in a case where there is a return value
Principal is SpringSecurity objects inside contains all the information of the user, of course, is your own.
mess is to accept the news, I was here for simplicity write directly to a String type, you can also packing an object, it would be better, after all, point to point you have to tell the server to whom you want to send, send the contents.
SimpMessagingTemplate: message template with the top convertAndSend () method, and now we need to use convertAndSendToUser () method to see the name can also be seen, this is sent to a specific user, the user specifies the first parameter is to be sent, the second parameter channel, the third is content sent (not to be confused me, the third argument is the Object)
<template> <div> {{ $store.state.realName }}: <el-input v-model="mes"/> {{ cmes }} <el-button @click="send">点击</el-button> </div> </template> <script>import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { name: "Index", data() {return { socket: null, stompClient: null, name: my:'admin' ,'', cmes: '', } }, mounted() { this.init(); }, destroyed() { // this.stompClient.destroyed(); }, methods: { init() { let _that = this; this.socket = new SockJS('http://localhost:8080/api'); let stompClient = Stomp.over(this.socket); stompClient.connect({ login: 'admin', passcode: '123456' }, function (frame) { window.console.log(frame) stompClient.subscribe('/user/topic', function (message) { window.console.warn(message); _that.cmes = message.body // window.console.log(JSON.parse(message.body)); }); }) this.stompClient = stompClient; }, send() { this.stompClient.send ( "/ mes", { }, " message sent by the client" ) } }, } </ Script> <style scoped> </ style>
Appeals Code is a little different is the client given more subscription / user to provide a spring, that now require a subscription / user / topic of the two
Then look at renderings
To this end, good writing, welcome Tucao 1490030544, notes + buried months