java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot WebSocket 多人聊天

SpringBoot+WebSocket实现多人在线聊天案例实例

作者:#Hideonbush

本文主要介绍了SpringBoot+WebSocket实现多人在线聊天案例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

1.pom.xml

<?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.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>chat01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chat01</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
<!--            <version>0.48</version>-->
        </dependency>
    </dependencies>

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

</project>

2.消息实体类

package com.yl.chat01.domain;

import java.io.Serializable;

public class Message implements Serializable {
    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;
    }

    @Override
    public String toString() {
        return "Message{" +
                "name='" + name + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

3.controller

package com.yl.chat01.controller;

import com.yl.chat01.domain.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) {
        return message;
    }
}

4.WebSocket的配置文件

package com.yl.chat01.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
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    // 注册端点,用于前端建立连接的
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
    }

    // 配置消息代理,通过广播的形式来传递消息
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
    }
}

5.前端发送消息页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>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="username">请输入用户名:</label>
    <input type="text" id = "username" placeholder="用户名"/>
</div>

<div>
    <input type="button" value="连接" id="connect"/>
    <input type="button" value="断开连接" id="disconnect" disabled="disabled"/>
</div>
<div id="chat"></div>

<div>
    <label for="content">请输入聊天内容</label>
    <input type="text" id="content" placeholder="聊天内容"/>
</div>
<input type="button" value="发送" disabled="disabled" id="send"/>

<script>
    var stompClient;
    $(function () {
        //连接
        $("#connect").click(function () {
            connect()
        })
        //发送消息到后台
        $("#send").click(function () {
            stompClient.send("/hello",{},JSON.stringify({'name':$('#username').val(),'content':$("#content").val()}))
        })

        //断开连接
        $("#disconnect").cilck(function () {
            stompClient.disconnect();
            disableButton(false);
        })

    })
    function connect() {
        if (!$("#username").val()) {
            alert("请输入用户名")
            return;
        }

        //获取连接地址
        var socketjs = new SockJS("/chat");
        stompClient = Stomp.over(socketjs);
        //建立连接
        stompClient.connect({},function (frame) {
            alert("connect success")
            disableButton(true);
            //订阅消息
            stompClient.subscribe("/topic/greetings",function (obj) {
                var msg = JSON.parse(obj.body);
                $("#chat").append("<div>"+msg.name+ ":" + msg.content+"</div>")
            })
        })
    }

    function disableButton(connected) {
        $("#connect").prop("disabled",connected);
        $("#disconnect").prop("disabled",!connected);
        $("#send").prop("disabled",!connected);
    }
</script>
</body>
</html>

6.测试

6.1.客户端A

在这里插入图片描述

6.2.客户端B

在这里插入图片描述

 到此这篇关于SpringBoot+WebSocket实现多人在线聊天案例实例的文章就介绍到这了,更多相关SpringBoot WebSocket 多人聊天内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文