Java实战之用springboot+netty实现简单的一对一聊天
作者:caiyang2015 发布时间:2023-12-03 07:28:19
标签:Java,springboot,netty,聊天,一对一聊天
一、引入pom
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.chat.info</groupId>
<artifactId>chat-server</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.33.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、创建netty 服务端
package com.chat.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
@Slf4j
public class ChatServer {
private EventLoopGroup bossGroup;
private EventLoopGroup workGroup;
private void run() throws Exception {
log.info("开始启动聊天服务器");
bossGroup = new NioEventLoopGroup(1);
workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChatServerInitializer());
//启动服务器
ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
log.info("开始启动聊天服务器结束");
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
/**
* 初始化服务器
*/
@PostConstruct()
public void init() {
new Thread(() -> {
try {
run();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
@PreDestroy
public void destroy() throws InterruptedException {
if (bossGroup != null) {
bossGroup.shutdownGracefully().sync();
}
if (workGroup != null) {
workGroup.shutdownGracefully().sync();
}
}
}
package com.chat.server;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class ChatServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//使用http的编码器和解码器
pipeline.addLast(new HttpServerCodec());
//添加块处理器
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
//自定义handler,处理业务逻辑
pipeline.addLast(new ChatServerHandler());
}
}
package com.chat.server;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chat.config.ChatConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
@Slf4j
public class ChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
//传过来的是json字符串
String text = textWebSocketFrame.text();
JSONObject jsonObject = JSON.parseObject(text);
//获取到发送人的用户id
Object msg = jsonObject.get("msg");
String userId = (String) jsonObject.get("userId");
Channel channel = channelHandlerContext.channel();
if (msg == null) {
//说明是第一次登录上来连接,还没有开始进行聊天,将uid加到map里面
register(userId, channel);
} else {
//有消息了,开始聊天了
sendMsg(msg, userId);
}
}
/**
* 第一次登录进来
*
* @param userId
* @param channel
*/
private void register(String userId, Channel channel) {
if (!ChatConfig.concurrentHashMap.containsKey(userId)) { //没有指定的userId
ChatConfig.concurrentHashMap.put(userId, channel);
// 将用户ID作为自定义属性加入到channel中,方便随时channel中获取用户ID
AttributeKey<String> key = AttributeKey.valueOf("userId");
channel.attr(key).setIfAbsent(userId);
}
}
/**
* 开发发送消息,进行聊天
*
* @param msg
* @param userId
*/
private void sendMsg(Object msg, String userId) {
Channel channel1 = ChatConfig.concurrentHashMap.get(userId);
if (channel1 != null) {
channel1.writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + msg));
}
}
/**
* 一旦客户端连接上来,该方法被执行
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
log.info("handlerAdded 被调用" + ctx.channel().id().asLongText());
}
/**
* 断开连接,需要移除用户
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
removeUserId(ctx);
}
/**
* 移除用户
*
* @param ctx
*/
private void removeUserId(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
AttributeKey<String> key = AttributeKey.valueOf("userId");
String userId = channel.attr(key).get();
ChatConfig.concurrentHashMap.remove(userId);
log.info("用户下线,userId:{}", userId);
}
/**
* 处理移除,关闭通道
*
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
三、存储用户channel 的map
package com.chat.config;
import io.netty.channel.Channel;
import java.util.concurrent.ConcurrentHashMap;
public class ChatConfig {
public static ConcurrentHashMap<String, Channel> concurrentHashMap = new ConcurrentHashMap();
}
四、客户端html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var socket;
//判断当前浏览器是否支持websocket
if (window.WebSocket) {
//go on
socket = new WebSocket("ws://localhost:7000/chat");
//相当于channelReado, ev 收到服务器端回送的消息
socket.onmessage = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + ev.data;
}
//相当于连接开启(感知到连接开启)
socket.onopen = function (ev) {
var rt = document.getElementById("responseText");
rt.value = "连接开启了.."
var userId = document.getElementById("userId").value;
var myObj = {userId: userId};
var myJSON = JSON.stringify(myObj);
socket.send(myJSON)
}
//相当于连接关闭(感知到连接关闭)
socket.onclose = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "连接关闭了.."
}
} else {
alert("当前浏览器不支持websocket")
}
//发送消息到服务器
function send(message) {
if (!window.socket) { //先判断socket是否创建好
return;
}
if (socket.readyState == WebSocket.OPEN) {
//通过socket 发送消息
var sendId = document.getElementById("sendId").value;
var myObj = {userId: sendId, msg: message};
var messageJson = JSON.stringify(myObj);
socket.send(messageJson)
} else {
alert("连接没有开启");
}
}
</script>
</head>
<body>
<h1 th:text="${userId}"></h1>
<input type="hidden" th:value="${userId}" id="userId">
<input type="hidden" th:value="${sendId}" id="sendId">
<form onsubmit="return false">
<textarea name="message" style="height: 300px; width: 300px"></textarea>
<input type="button" value="发送" onclick="send(this.form.message.value)">
<textarea id="responseText" style="height: 300px; width: 300px"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
五、controller 模拟用户登录以及要发送信息给谁
package com.chat.controller;
import com.chat.config.ChatConfig;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ChatController {
@GetMapping("login")
public String login(Model model, @RequestParam("userId") String userId, @RequestParam("sendId") String sendId) {
model.addAttribute("userId", userId);
model.addAttribute("sendId", sendId);
return "chat";
}
@GetMapping("sendMsg")
public String login(@RequestParam("sendId") String sendId) throws InterruptedException {
while (true) {
Channel channel = ChatConfig.concurrentHashMap.get(sendId);
if (channel != null) {
channel.writeAndFlush(new TextWebSocketFrame("test"));
Thread.sleep(1000);
}
}
}
}
六、测试
登录成功要发消息给bbb
登录成功要发消息给aaa
来源:https://blog.csdn.net/u014190164/article/details/116093343


猜你喜欢
- Jedis简介实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis,对于主流语言,Redis都提供了对应的客户端;提供
- 1.初衷是由于调用银行接口的批量处理接口时,每次最多只能处理500条数据,但是当数据总数为510条时。我又不想第一次调用处理500条,第二次
- 在logback.xml中加上该配置,包名如:com.xxx<logger name="packageName"
- 1.向上转型 向下转型2.强制类型转换的应用应用多态性时由于引用为父类类型,导致编译时只能调用父类中声明的属性和方法。子类特有的属性和方法不
- 本文实例为大家分享了java代码统计小程序,供大家参考,具体内容如下可以测试每周你的工作量package rexExp;import jav
- 泛型中占位符T和?有什么区别?这是一个好问题,有的人可能弄不清楚,所以我们这里简单的演示一下,相信大家一定能弄清楚的!先上两段代码:publ
- Word中设置水印时,可加载图片设置为水印效果,但通常添加水印效果时,会对所有页面都设置成统一效果,如果需要对每一页或者某个页面设置不同的水
- 1 安装 Unity安装Unity Hub安装 Unity 推荐使用 Unity Hub 管理程序(官方管理程序)。Unity Hub 是一
- 访问修饰符private缺省protected public 作用范围访问修饰符\作用范围所在类同一包内其他类其他包内子类其他包内非子类pr
- 一、什么是Activity?简单的说:Activity就是布满整个窗口或者悬浮于其他窗口上的交互界面。在一个应用程序中通常由多个Activi
- 前言本文介绍在spring mvc中非常重要的注解@ModelAttribute.这个注解可以用在方法参数上,或是方法声明上。这个注解的主要
- //********************************************************** //******主
- 现阶段的问题现在是云原生和容器化时代,.NET Core对于云原生来说有非常好的兼容和亲和性,dotnet社区以及微软为.NET Core提
- 1、本篇内容本文让大家掌握 springmvc 中异步处理请求,特别牛逼的一个功能,大家一定要掌握。2、看段代码,分析问题@Response
- 参考dubbo和shenyu网关实现自定义的SPISPI标注注解标注提供SPI能力接口的注解@Documented@Retention(Re
- menu部分xml代码<?xml version="1.0" encoding="utf-8"
- PagerBottomTabStrip 是一个基本按谷歌Material Design规范完成的安卓底部导航栏控件官方设计规范:https:
- 使用Spring3 实现用户登录以及权限认证这里我就简单介绍一下,我在实现的时候处理的一些主要的实现。1.用户登录 <form act
- Spring框架是一个优秀的多层J2EE系统框架,Spring本身没有提供对系统的安全性支持。Acegi是基于Spring IOC 和 AO
- 1、静态代码块①、格式在java类中(方法中不能存在静态代码块)使用static关键字和{}声明的代码块:public class Code