An article takes you to use SpringBoot to get the implementation of WebSocket-based online group chat

One, add dependency

Insert picture description here
Add the dependencies needed for the front end:

	 <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>sockjs-client</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>stomp-websocket</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>

Two, configure WebSocketConfig

@Configuration
//开启使用STOMP协议来传输基于代理的消息,Broker就是代理的意思
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    
    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    
    
        //定义消息代理的前缀
        registry.enableSimpleBroker("/topic");
        //配置一个或者多个前缀,过滤出需要代理方法处理的消息
        registry.setApplicationDestinationPrefixes("/app");
    }

    /**
     * 注册STOMP协议的节点,并指定映射的URL
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    
    
        //注册STOMP协议节点,同时指定使用 SockJS 协议
        registry.addEndpoint("/chat").withSockJS();
    }
}

Three, configure the Message class

The Message class is used to receive information sent by the browser

public class Message {
    
    
    private String name;
    private String content;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getContent() {
    
    
        return content;
    }

    public void setContent(String content) {
    
    
        this.content = content;
    }
}

Fourth, configure the controller GreetingController

@Controller
public class GreetingController {
    
    
    /**
     * 这个方法用来处理浏览器发送来的消息,对其进行处理
     * @param message
     * @return
     */
    //@MessageMapping 类似 @RequestMapping
    @MessageMapping("/hello")
    //处理完之后对其进行转发到 SendTo 中的路径
    @SendTo("/topic/greetings")
    public Message greeting(Message message) {
    
    
        return message;
    }
}

Here you can also be used SimpMessagingTemplateto set:

@Controller
public class GreetingController {
    
    
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;
    @MessageMapping("/hello")
    public void greeting(Message message) {
    
    
        simpMessagingTemplate.convertAndSend("/topic/greetings", message);
    }
}

SimpMessagingTemplateThis class mainly implements the function of sending messages to the browser.

Five, set the front-end page chat.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>群聊</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>

<table>
    <tr>
        <td>请输入用户名</td>
        <td><input type="text" id="name"></td>
    </tr>
    <tr>
        <td><input type="button" id="connect" value="连接"></td>
        <td><input type="button" id="disconnect" disabled="disabled" value="断开连接"></td>
    </tr>
</table>
<div id="chat" style="display: none">
    <table>
        <tr>
            <td>请输入聊天内容</td>
            <td><input type="text" id="content"></td>
            <td><input type="button" id="send" value="发送"></td>
        </tr>
    </table>
    <div id="conversation">群聊进行中...</div>
</div>
<script>
    $(function () {
    
    
        $("#connect").click(function () {
    
    
            connect();
        })
        $("#disconnect").click(function () {
    
    
            if (stompClient != null) {
    
    
                stompClient.disconnect();
            }
            setConnected(false);
        })

        $("#send").click(function () {
    
    
            //将消息发送到代理方法内
            stompClient.send('/app/hello',{
    
    },JSON.stringify({
    
    'name':$("#name").val(),'content':$("#content").val()}))
        })
    })

    var stompClient = null;

    function connect() {
    
    
        if (!$("#name").val()) {
    
    
            return;
        }
        //建立连接
        var socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        //建立连接
        stompClient.connect({
    
    }, function (success) {
    
    
            setConnected(true);
            stompClient.subscribe('/topic/greetings', function (msg) {
    
    
                //拿到输入的消息内容进行展示
                showGreeting(JSON.parse(msg.body));
            });
        })
    }
    //展示消息的内容
    function showGreeting(msg) {
    
    
        $("#conversation").append('<div>' + msg.name + ':' + msg.content + '</div>');
    }
    //设置连接按钮,已经连接上则禁止,反之不禁止
    function setConnected(flag) {
    
    
        $("#connect").prop("disabled", flag);
        $("#disconnect").prop("disabled", !flag);
        //连接上,才显示聊天区的内容
        if (flag) {
    
    
            $("#chat").show();
        } else {
    
    
            $("#chat").hide();
        }
    }
</script>
</body>
</html>

Six, login test

Open two browsers to realize the group chat function:

Insert picture description here

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108928895