websocket实现消息群发

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.czh</groupId>
    <artifactId>websocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>websocket</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>sockjs-client</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>stomp-websocket</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置websocket

package com.czh.websocket.config;

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;

@Configuration
@EnableWebSocketMessageBroker//开启websocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
       /* config.enableSimpleBroker("/topic")
        标识消息代理的前缀,即如果有消息的前缀是“topic”,就会给
        消息代理broker,再有消息代理将消息广播给当前连接的客户端*/
        config.enableSimpleBroker("/topic");
        /*config.setApplicationDestinationPrefixes("/app")
        表示配置一个或多个前缀,通过这些前缀过滤出需要被注解方法处理的消息

        * */
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
    }
}

定义Controller

package com.czh.websocket.controller;


import com.czh.websocket.model.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class GreetingController {
    @MessageMapping("hello")
    @SendTo("/topic/greetings")
    public Message greeting(Message message)throws Exception{
        return message;
    }
}

页面

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>
<div>
    <label for="name">请输入用户名:label>
    <input type="text" id="name" placeholder="用户名">
div>
<div>
    <button id="connect" type="button">连接button>
    <button id="disconnect" type="button" disabled="disabled">断开连接button>
div>
<div id="chat" style="display: none;">
    <div>
        <label for="name">请输入聊天内容:label>
        <input type="text" id="content" placeholder="聊天内容">
    div>
    <button id="send" type="button">发送button>
    <div id="greetings">
        <div id="conversation" style="display: none">群聊进行中...div>
    div>
div>
<script>
    var stompClient = null;
    function setConnected(connected) {
        $("#connect").prop("disabled", connected);
        $("#disconnect").prop("disabled", !connected);
        if (connected) {
            $("#conversation").show();
            $("#chat").show();
        }
        else {
            $("#conversation").hide();
            $("#chat").hide();
        }
        $("#greetings").html("");
    }
    function connect() {
        if (!$("#name").val()) {
            return;
        }
        var socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            stompClient.subscribe('/topic/greetings', function (greeting) {
                showGreeting(JSON.parse(greeting.body));
            });
        });
    }
    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect();
        }
        setConnected(false);
    }
    function sendName() {
        stompClient.send("/app/hello",
            {},
            JSON.stringify({'name': $("#name").val(),'content':$("#content").val()}));
    }
    function showGreeting(message) {
        $("#greetings")
            .append("
" + message.name+":"+message.content + "
"
); } $(function () { $( "#connect" ).click(function() { connect(); }); $( "#disconnect" ).click(function() { disconnect(); }); $( "#send" ).click(function() { sendName(); }); });
script> body> html>

你可能感兴趣的:(websocket,网络协议,网络)