springboot + websocket achieve group chat

Creating springboot project, pom.xml file depend on the introduction of socket

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

Create a socket core configuration class

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpointSang").withSockJS(); //添加终点
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");//开启top代理
    }
}

Create a controller

@Controller
 public  class WebSocketController { 
    
    @MessageMapping ( "/ is available for purchase")   // the request / welcomel sent 
    @SendTo ( "/ Topic / getResponse") // sent to the subscription Topic / getResponse 
    public String getMessage (String name) { 
        System.out.println (name); 
        return name; 
    } 
}

Create index.html page, remember to introduce relevant js file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket广播</title>
    <script src="jquery-3.4.1.js"></script>
    <script src="sockjs.min.js"></script>
    <script src="stomp.js"></script>
</head>
<body>

<button type="button" onclick="connent()">连接</button>
<input type="text" id="name"/>
<button type="button" onclick="sendMsg()">发送</button>
<script>

    var stompClient=null;

    //连接socket
    function connent() {
        var socket = new SockJS("/endpointSang");
        stompClient= Stomp.over(socket);
        stompClient.connect({},function (frame) {
            stompClient.subscribe("/topic/getResponse",function (response) {
                console.log(response)
            })
        })
    }

    //断开连接
    function disConnent() {
        if (stompClient!=null) {
            stompClient.disconnect();
        }
    }

    //发送数据
    function  sendMsg() {
        var name = $("#name").val();
        stompClient.send("/welcome",{},JSON.stringify({"name":name}));
    }


</script>

</body>
</html>

Click connection

 

 After sending the data

 

 As long as the subscription / topic / getResponse can receive the data.

This, group chat demo completed.

Source address: https://github.com/duanbochao/websocket.git

Guess you like

Origin www.cnblogs.com/gfbzs/p/12576030.html