websocket 是一个全双工的长连接通讯
话不多说直接上代码。。
服务端的代码实现
public void init() throws InterruptedException {
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup, workGroup).channel(NIOServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
// http 编码和解编码 handler
pipeline.addLast(new HttpServerCodec());
// chunked 以块的形式 handler
pipeline.addLast(new ChunkedWriteHandler());
// http 数据传输过程中是分段的, httpObjectAggregator 就可以给多个段做聚合操作,这就是浏览器发送大量数据时候,就会发出多次 http 请求
pipeline.addLast(new HttpObjectAggregator(8192));
// webSocket 是通过帧的形式传递的,可以看到 WebSocketFrame 六个子类,WebSocketServerProtocolHandler 他的主要功能就是可以把 http 协议升级为 ws 协议,保持长连接
pipeline.addLast(new WebSocketServerProtocolHandler("/msg"));
pipeline.addLast(new CustomWebSocketFrameTextHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(88).sync();
channelFuture.addListener(future -> {
if (future.isDone()) log.info("端口绑定成功");
});
channelFuture.channel().closeFuture().sync();
} finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
服务端的逻辑会用到自定义handler的处理器
CustomWebSocketFrameTextHandler 这个自定义处理器。
处理器的代码
/**
* 这里的 {@link TextWebSocketFrame} 表示一个文本帧
*
* @author L
*/
class CustomWebSocketFrameTextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
Logger log = LoggerUtils.getLogger(CustomWebSocketFrameTextHandler.class);
/**
* 当 web 客户端连接以后就会触发这个方法
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
// id 表示唯一的值信息,LongText 是唯一的。ShortText 不是唯一的
log.info("handlerAdded => {} 被调用", ctx.channel().id().asLongText());
log.info("handlerAdded => {} 被调用", ctx.channel().id().asShortText());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
String text = msg.text();
log.info("{}", text);
// 回复客户端消息
ctx.writeAndFlush(new TextWebSocketFrame(text));
}
/**
* 断开连接以后会触发
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
log.info("handlerRemoved => {} 被调用", ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("发生异常 => {}", cause.getMessage());
}
}
服务端这就可以运行了。然后需要一个客户端来测试。客户端需要直接编写一个 html 的简单的小页面来测试。
let webSocket = null;
if (window.WebSocket) {
// 逻辑
webSocket = new WebSocket("ws://localhost:88/msg");
webSocket.onopen = () => {
let showPlace = document.getElementById("responseMessage");
showPlace.value = "连接开启";
}
webSocket.onmessage = function (p) {
let showPlace = document.getElementById("responseMessage");
showPlace.value = showPlace.value + "rn" + p.data;
}
webSocket.onclose = () => {
let showPlace = document.getElementById("responseMessage");
showPlace.value = showPlace.value + "rn" + "连接关闭";
}
webSocket.onerror = (p) => {
let showPlace = document.getElementById("responseMessage");
showPlace.value = showPlace.value + "rn" + "连接错误 => " + p.type;
}
} else alert("当前浏览器不支持操作");
function send(msg) {
if (webSocket.OPEN) {
webSocket.send(msg);
}
}
这样就实现了 netty的 websocket 服务