49 lines
1.9 KiB
Java
49 lines
1.9 KiB
Java
package com.example.demo.Service;
|
|
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
import io.netty.channel.SimpleChannelInboundHandler;
|
|
import io.netty.channel.group.ChannelGroup;
|
|
import io.netty.channel.group.DefaultChannelGroup;
|
|
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
|
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
|
|
import io.netty.util.concurrent.GlobalEventExecutor;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
@Component
|
|
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
|
|
|
|
// 管理所有连接的WebSocket通道
|
|
private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
|
|
|
|
private WebSocketServerHandshaker webSocketServerHandshaker;
|
|
@Override
|
|
public void handlerAdded(ChannelHandlerContext ctx) {
|
|
channels.add(ctx.channel());
|
|
channels.writeAndFlush(new TextWebSocketFrame("[客户端] - " + ctx.channel().remoteAddress() + " 加入聊天室"));
|
|
}
|
|
|
|
@Override
|
|
public void handlerRemoved(ChannelHandlerContext ctx) {
|
|
channels.remove(ctx.channel());
|
|
channels.writeAndFlush(new TextWebSocketFrame("[客户端] - " + ctx.channel().remoteAddress() + " 离开聊天室"));
|
|
}
|
|
|
|
@Override
|
|
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
|
|
// 广播消息到所有客户端
|
|
channels.forEach(ch -> {
|
|
if (ch != ctx.channel()) {
|
|
ch.writeAndFlush(new TextWebSocketFrame("[客户端] " + ctx.channel().remoteAddress() + " 说:" + msg.text()));
|
|
} else {
|
|
ch.writeAndFlush(new TextWebSocketFrame("[你] 说:" + msg.text()));
|
|
}
|
|
});
|
|
}
|
|
|
|
@Override
|
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
|
cause.printStackTrace();
|
|
ctx.close();
|
|
}
|
|
}
|