ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

在线聊天室的消息单聊的实现——springboot整合WebSocket(二)

2021-07-05 23:33:56  阅读:314  来源: 互联网

标签:function WebSocket springboot org springframework chat 单聊 import public


一、声明

项目的搭建请大家移步到:在线聊天室的消息群聊的实现——springboot整合WebSocket(一)

单聊的实现是在群聊项目上进行延申改造的。

二、引入依赖

在这里插入图片描述

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

三、设置用户配置类

在这里插入图片描述

package com.tony.websocket.config;

import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: SecurityConfig
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/22:18
 * @Description: 登录配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

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

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

四、修改消息代理配置类

在这里插入图片描述

五、创建单聊消息实体

在这里插入图片描述

package com.tony.websocket.bean;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: Chat
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/22:31
 * @Description: 单聊消息对象
 */
public class Chat {

    private String from;
    private String content;
    private String to;

    public String getFrom() {
        return from;
    }

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

    public String getContent() {
        return content;
    }

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

    public String getTo() {
        return to;
    }

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

六、创建controller

在这里插入图片描述

package com.tony.websocket.controller;

import com.tony.websocket.bean.Chat;
import com.tony.websocket.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: GreetingController
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/20:35
 * @Description:
 */
@Controller
public class GreetingController {

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

    /**
    * @Description: chat 单聊的实现
    * @Param: [principal 消息从何用户而来, chat]
    * @return: void
    * @Author: 皮蛋布丁
    * @Date: 2021/7/5 22:30
    */
    @MessageMapping("/chat")
    public void chat(Principal principal, Chat chat) {
        //消息从哪来
        chat.setFrom(principal.getName());
        //消息发送给目标用户(参数1:发送用户;参数2:发送地址;参数3:发送消息对象)
        simpMessagingTemplate.convertAndSendToUser(chat.getTo(),"/queue/chat",chat);
    }
}

七、构建聊天界面

在这里插入图片描述

<!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>
    <input type="button" id="connect" value="连接">
        <!--            disabled="disabled":默认不可点击-->
    <input type="button" id="disconnect" disabled="disabled" value="断开连接">
    <hr>
    消息内容:<input type="text" id="content">目标用户:<input type="text" id="to"><input type="button" value="发送" id="send">
    <div id="conversation"></div>
<script>
    <!--    定义连接方法-->
    $(function () {
        //连接按钮事件
        $("#connect").click(function () {
            connect();
        })

        //断开连接按钮事件
        $("#disconnect").click(function () {
            if (stompClient != null) {
                //断开连接
                stompClient.disconnect();
            }
            //恢复按钮状态
            setConnection(false);
        })

        //发送按钮点击事件
        $("#send").click(function () {
            //发送消息(参数1:发送地址;参数2:消息优先级;参数3:JSON消息对象)
            stompClient.send('/app/chat',{},JSON.stringify({'to':$('#to').val(),'content':$('#content').val()}))
        })
    })

    var stompClient = null;

    function connect() {
        //建立连接
        var socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        //参数1:建立优先级;参数2:连接成功的回调;参数3:连接失败的回调
        stompClient.connect({},function (success) {
            //设置按钮状态
            setConnection(true);
            //订阅服务器上的消息
            //参数1:服务器上的地址;参数2:服务器收到的消息
            stompClient.subscribe('/user/queue/chat',function (msg) {
                showGreeting(JSON.parse(msg.body));
            })
        })
    }

    function setConnection(flag) {
        //参数1:属性;参数2:设置状态
        $("#connect").prop("disabled",flag);
        $("#disconnect").prop("disabled",!flag);
        //显示div
        if (flag) {
            $("#chat").show();  //显示
        } else {
            $("#chat").hide();  //隐藏
        }
    }

    function showGreeting(msg) {
        $("#conversation").append('<div>' + msg.from + ':' + msg.content + '</div>');
    }

</script>

</body>
</html>

八、运行

1、登录

在这里插入图片描述

2、建立连接

在这里插入图片描述

3、发送消息

发送的用户必须是正确的,且已连接才能收到发送的消息。
在这里插入图片描述

注:能力有限,还请谅解,争取早日能够写出有质量的文章!

我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。

在这里插入图片描述

感谢各位大佬光临寒舍~

标签:function,WebSocket,springboot,org,springframework,chat,单聊,import,public
来源: https://blog.csdn.net/qq_42700766/article/details/118500075

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有