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

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值