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

一、声明

项目的搭建请大家移步到:在线聊天室的消息群聊的实现——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、发送消息

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

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

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

在这里插入图片描述

感谢各位大佬光临寒舍~

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值