WebSocket was introduced in the last article, this time using WebSocket to achieve a simple page chat function.

To prepare

Note: WebSocket is not supported in Tomcat6 and was only supported in Tomcat7. Normal JaveEE and JSPServlet projects also do not support WebSocket and need to copy additional JAR packages

Related,

Here you can add dependencies directly to a SpringBoot project when you create it using development tools

The JS required for the preceding section

code

The background Configuration

This is where the basic WebSocket configuration is performed

@Configuration
@EnableWebSocketMessageBroker // Enable the information broker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /** * Configures connection point information *@param registry
     */
    @Override
    public void  registerStompEndpoints(StompEndpointRegistry registry){
        // join point, where withSockJS() is the front section library
        registry.addEndpoint("/ws/ep").withSockJS();    
    }

    /** * Configure message queue (broker) *@param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // Start the broker, where you can configure more than one. /queue stands for point-to-point messages
        registry.enableSimpleBroker("/queue"); }}Copy the code

Background the Controller

@Controller // Note that the Controller annotation is used here, not RestController
public class WsController {
    // As soon as the WebSocket dependency is introduced, the Bean is automatically registered
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;   

    /** * This method is used to receive messages sent from the client. The parameters are the message itself. The communication protocol can be customized, i.e. the format of the parameters can be customized@param msg
     * @paramPrincipal holds user information */
    @MessageMapping("/ws/chat") // Message mapping
    public void receiveMessage(String msg,Principal principal){
        // The string sent from the previous section passes; Number to split the last string (the client that needs to receive the message)
        String[] split = msg.split(";");
        Map<String,Object>map = new HashMap<>();
        map.put("msg",split[0]);
        map.put("username",split[split.length-1]);
        // split[split.length-1] The client that receives the message
        / / "/ queue/MSG" queue
        simpMessagingTemplate.convertAndSendToUser(split[split.length-1]."/queue/msg",map); }}Copy the code

The front

I’m not going to introduce the previous paragraph here, but give a general description

<template>
  <div>
    <div style="margin-top: 20px">
      <div v-for = "(m,index) in ms" :key="index">{{m.username}}:{{m.msg}}</div>
    </div>
    <el-input v-model="msg"></el-input>
    <! Send data to the background by clicking on the trigger sendMsg() method -->
    <el-button @click = "sendMsg">send</el-button>
  </div>
</template>

<script>
  / / for JS
  import '.. /.. /lib/sockjs'
  import '.. /.. /lib/stomp'

  export default {
    name: "FriendChat",
    data(){
      return {
        msg:' '.ms: [].stomp:null
      }
    },
    mounted(){
      // The connection is obtained through initCon() when the page is rendered
      this.initCon();
    },
    methods:{
      initCon(){
        let _this=this;
        this.stomp = Stomp.over(new SockJS('/ws/ep'));
        this.stomp.connect({},success => {
          _this.stomp.subscribe("/user/queue/msg",msg =>{
            _this.ms.push(JSON.parse(msg.body));
          })
        },fail =>{

        })
      },
      sendMsg(){
        this.stomp.send("/ws/chat",{ },this.msg)
      }
    }
  }
</script>

<style scoped>
</style>
Copy the code

The effect

Here we test sending messages with two different users

Make sure the protocol is upgraded and the connection is obtained through the console