需求:站內聊天的實現。
分析過程:1、websocket實現的功能簡單,缺點在多人的情況下效率會幾何數降低。
2、Netty4比Netty5更穩定,測試發現Netty5暫時不穩定,內存處理不如Netty4
實現:
1、pom.xml配置
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.63.Final</version>
</dependency>
2、配置類
package com.xxx.chat.room.configs;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.concurrent.ConcurrentHashMap;
/**
* 配置類
* @author liuyue
* @date 2024/3/20 16:38
*/
public class NettyConfig {
/**
* 定義一個channel組,管理所有的channel
* GlobalEventExecutor.INSTANCE 是全局的事件執行器,是一個單例
*/
private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
/**
* 存放用戶與Chanel的對應信息,用於給指定用戶發送消息
*/
private static final ConcurrentHashMap<String, Channel> USER_CHANNEL_MAP = new ConcurrentHashMap<>();
private NettyConfig() {
}
/**
* 獲取channel組
*/
public static ChannelGroup getChannelGroup() {
return CHANNEL_GROUP;
}
/**
* 獲取用戶channel map
*/
public static ConcurrentHashMap<String, Channel> getUserChannelMap() {
return USER_CHANNEL_MAP;
}
}
3、NettyServer對外提供訪問的socket
package com.xxx.chat.room;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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.codec.serialization.ObjectEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
@Component
@Slf4j
public class NettyServer {
/**
* webSocket協議名
*/
private static final String WEBSOCKET_PROTOCOL = "WebSocket";
/**
* 端口號
*/
@Value("${netty.port: 9998}")
private int port;
/**
* webSocket路徑
*/
@Value("${netty.path: /webSocket}")
private String webSocketPath;
@Autowired
private WebSocketHandler webSocketHandler;
private EventLoopGroup bossGroup;
private EventLoopGroup workGroup;
/**
* 啓動
*
* @throws InterruptedException
*/
private void start() throws InterruptedException {
bossGroup = new NioEventLoopGroup();
workGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
// bossGroup輔助客戶端的tcp連接請求, workGroup負責與客戶端之前的讀寫操作
bootstrap.group(bossGroup, workGroup);
// 設置NIO類型的channel
bootstrap.channel(NioServerSocketChannel.class);
// 設置監聽端口
bootstrap.localAddress(new InetSocketAddress(port));
// 連接到達時會創建一個通道
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 流水線管理通道中的處理程序(Handler),用來處理業務
// webSocket協議本身是基於http協議的,所以這邊也要使用http編解碼器
ch.pipeline().addLast(new HttpServerCodec());
ch.pipeline().addLast(new ObjectEncoder());
// 以塊的方式來寫的處理器
ch.pipeline().addLast(new ChunkedWriteHandler());
/*
說明:
1、http數據在傳輸過程中是分段的,HttpObjectAggregator可以將多個段聚合
2、這就是爲什麼,當瀏覽器發送大量數據時,就會發送多次http請求
*/
ch.pipeline().addLast(new HttpObjectAggregator(8192));
/*
說明:
1、對應webSocket,它的數據是以幀(frame)的形式傳遞
2、瀏覽器請求時 ws://localhost:58080/xxx 表示請求的uri
3、核心功能是將http協議升級爲ws協議,保持長連接
*/
ch.pipeline().addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL,
true,
65536 * 10));
// 自定義的handler,處理業務邏輯
ch.pipeline().addLast(webSocketHandler);
}
});
// 配置完成,開始綁定server,通過調用sync同步方法阻塞直到綁定成功
ChannelFuture channelFuture = bootstrap.bind().sync();
log.info("Server started and listen on:{}", channelFuture.channel().localAddress());
// 對關閉通道進行監聽
channelFuture.channel().closeFuture().sync();
}
/**
* 釋放資源
*
* @throws InterruptedException
*/
@PreDestroy
public void destroy() throws InterruptedException {
if (bossGroup != null) {
bossGroup.shutdownGracefully().sync();
}
if (workGroup != null) {
workGroup.shutdownGracefully().sync();
}
}
@PostConstruct()
public void init() {
//需要開啓一個新的線程來執行netty server 服務器
new Thread(() -> {
try {
start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
4、WebSocketHandler消息處理
package com.hake.chat.room;
import com.hake.chat.room.configs.NettyConfig;
import io.netty.channel.ChannelHandler;
import org.springframework.stereotype.Component;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final Logger log = LoggerFactory.getLogger(NettyServer.class);
/**
* @param ctx 上下文
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
log.info("handlerAdded 被調用"+ctx.channel().id().asLongText());
// 添加到channelGroup 通道組
NettyConfig.getChannelGroup().add(ctx.channel());
}
/**
* 讀取數據
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
log.info("服務器收到消息:{}",msg.text());
//獲取用戶ID,關聯channel
JSONObject jsonObject = JSONUtil.parseObj(msg.text());
String uid = jsonObject.getStr("userId");
NettyConfig.getUserChannelMap().put(uid,ctx.channel());
// 將用戶ID作爲自定義屬性加入到channel中,方便隨時channel中獲取用戶ID
AttributeKey<String> key = AttributeKey.valueOf("userId");
ctx.channel().attr(key).setIfAbsent(uid);
// 回覆消息
ctx.channel().writeAndFlush(new TextWebSocketFrame("服務器連接成功!"));
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
log.info("handlerRemoved 被調用"+ctx.channel().id().asLongText());
// 刪除通道
NettyConfig.getChannelGroup().remove(ctx.channel());
removeUserId(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.info("異常:{}",cause.getMessage());
// 刪除通道
NettyConfig.getChannelGroup().remove(ctx.channel());
removeUserId(ctx);
ctx.close();
}
/**
* 刪除用戶與channel的對應關係
* @param ctx 上下文
*/
private void removeUserId(ChannelHandlerContext ctx){
AttributeKey<String> key = AttributeKey.valueOf("userId");
String userId = ctx.channel().attr(key).get();
NettyConfig.getUserChannelMap().remove(userId);
}
}
5、推送消息服務
package com.xxx.chat.room.service;
public interface PushService {
/**
* 推送給指定用戶
*
* @param userId 用戶ID
* @param msg 消息
*/
void pushMsgToOne(String userId, String msg);
/**
* 推送給所有用戶
*
* @param msg 消息
*/
void pushMsgToAll(String msg);
}
package com.xxx.chat.room.service.impl;
import com.hake.chat.room.configs.NettyConfig;
import com.hake.chat.room.service.PushService;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Service;
import io.netty.channel.Channel;
import java.util.concurrent.ConcurrentHashMap;
/**
* 推送消息服務
* @author liuyue
* @date 2024/3/21 9:30
*/
@Service
public class PushServiceImpl implements PushService {
@Override
public void pushMsgToOne(String userId, String msg){
ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
Channel channel = userChannelMap.get(userId);
channel.writeAndFlush(new TextWebSocketFrame(msg));
}
@Override
public void pushMsgToAll(String msg){
NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
}
}
6、controller接口
package com.hake.chat.room.controller;
import com.hake.chat.room.service.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 發送消息
* @author liuyue
* @date 2024/3/20 16:57
*/
@RestController
@RequestMapping("/push")
public class PushController {
@Autowired
private PushService pushService;
/**
* 推送給所有用戶
*
* @param msg 消息
*/
@PostMapping("/pushAll")
public void pushToAll(@RequestParam("msg") String msg) {
pushService.pushMsgToAll(msg);
}
/**
* 推送給指定用戶
*
* @param userId 用戶ID
* @param msg 消息
*/
@PostMapping("/pushOne")
public void pushMsgToOne(@RequestParam("userId") String userId, @RequestParam("msg") String msg) {
pushService.pushMsgToOne(userId, msg);
}
}
7、YML配置,簡單頁面配置
server:
port: 9997
spring:
application:
name: charroom
thymeleaf:
prefix: classpath:/html/ # 訪問html下的html文件需要配置模板,映射,路徑指向
suffix: .html
cache: false # 開發時關閉緩存,不然沒法看到實時頁面
mvc:
view:
prefix: /
suffix: .html
netty:
host: 127.0.0.1
port: 9998
path: /webSocket
8、html頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var socket;
// 判斷當前瀏覽器是否支持webSocket
if (window.WebSocket) {
socket = new WebSocket("ws://127.0.0.1:9998/webSocket")
// 相當於channel的read事件,ev 收到服務器回送的消息
socket.onmessage = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + ev.data;
}
// 相當於連接開啓
socket.onopen = function (ev) {
let userId = [[${userId}]];
console.info(userId);
var rt = document.getElementById("responseText");
rt.value = "連接開啓了..."
socket.send(
JSON.stringify({
// 連接成功將,用戶ID傳給服務端
userId: userId
})
);
}
// 相當於連接關閉
socket.onclose = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "連接關閉了...";
}
} else {
alert("當前瀏覽器不支持webSocket")
}
</script>
<form onsubmit="return false">
<textarea id="responseText" style="height: 150px; width: 300px;"></textarea>
<input type="button" value="清空內容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
簡單例子,如果要使用,需要集成到自己的項目。
每天進步一點點!