在线聊天室的消息单聊的实现——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、发送消息
发送的用户必须是正确的,且已连接才能收到发送的消息。
注:能力有限,还请谅解,争取早日能够写出有质量的文章!
我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。
感谢各位大佬光临寒舍~
标签:function,WebSocket,springboot,org,springframework,chat,单聊,import,public 来源: https://blog.csdn.net/qq_42700766/article/details/118500075