gpt4 book ai didi

SpringBoot + WebSocket实现点对点在线单聊案例

转载 作者:知者 更新时间:2024-03-13 08:13:12 27 4
gpt4 key购买 nike

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.4.2</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-security</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;
import java.util.Date;

public class Chat implements Serializable {
    private String from;
    private String to;
    private String content;
    private Date date;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getContent() {
        return content;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Chat{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", content='" + content + '\'' +
                ", date=" + date +
                '}';
    }
}

3.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").setAllowedOrigins("http://localhost:8080").withSockJS();
    }

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

4.Security的配置,配置用于登录的用户名和密码

package com.yl.chat01.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.inMemoryAuthentication()
               .withUser("admin")
               .password("{noop}123")
               .roles("admin")
               .and()
               .withUser("root")
               .password("{noop}123")
               .roles("admin");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin().permitAll();
    }
}

5.controller

package com.yl.chat01.controller;

import com.yl.chat01.domain.Chat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;
import java.util.Date;

@Controller
public class GreetingController {

//    /**
//     * 群聊
//     * @param message
//     * @return
//     */
//    @MessageMapping("/hello") //发送消息请求
//    @SendTo("/topic/greetings") //消息广播
//    public Message greeting(Message message) {
//        return message;
//    }

    //单聊发送消息模板
    @Autowired
    SimpMessagingTemplate  simpMessagingTemplate;

    /**
     * 单聊
     * @param principal
     * @param chat
     */
    @MessageMapping("/onlineChat")
    public void chat(Principal principal, Chat chat) {
        chat.setFrom(principal.getName());
        chat.setDate(new Date());
        simpMessagingTemplate.convertAndSendToUser(chat.getTo(),"/queue/chat",chat);
    }
    
}

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 id="chat"></div>
<div>
    <label for="username">请输入目标用户名:</label>
    <input type="text" id = "username" placeholder="用户名"/>
    <label for="content">请输入聊天内容</label>
    <input type="text" id="content" placeholder="聊天内容"/>
</div>

<input type="button" value="发送" id="send"/>

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

    function connect() {
        //获取连接地址
        var socketjs = new SockJS("/chat");
        stompClient = Stomp.over(socketjs);
        //建立连接
        stompClient.connect({},function (frame) {
            //订阅消息
            stompClient.subscribe("/user/queue/chat",function (obj) {
                var msg = JSON.parse(obj.body);
                $("#chat").append("<div>"+ "消息来自于:" +msg.from+ " ,消息内容为:" + msg.content+ " ,发送时间:" + msg.date+"</div>")
            })
        })
    }
</script>
</body>
</html>

6.测试

6.1 客户端A,用admin登录

6.2 客户端B,用root用户登录

6.3 互相发送消息
客户端A:

客户端B:

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com