使用Netty实现WebSocket的服务端部分
服务端代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class Myservice {
public static void main(String[] args) throws InterruptedException {
// 创建两个线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)) // 用于日志记录
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// 使用http的编解码器
pipeline.addLast(new HttpServerCodec());
// 加入块处理器
pipeline.addLast(new ChunkedWriteHandler());
/*
http数据在传输过程中是分段的,HttpObjectAggregator可以将多个段聚合起来
*/
pipeline.addLast(new HttpObjectAggregator(8192));
/*
对于webSocket的数据是使用帧的形式传递的
浏览器请求时,ws://localhost:7000/xxx
WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/xxx"));
// 自定义的handler
pipeline.addLast(new MyWebSocketFrameHandler());
}
});
ChannelFuture future = bootstrap.bind(7000).sync();
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
自定义处理类
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.time.LocalDateTime;
public class MyWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
System.out.println("服务器收到消息" + textWebSocketFrame.text());
// 回复消息
channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now() + textWebSocketFrame.text()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// longText唯一,shortText不唯一
System.out.println("handlerAdded 被调用" + ctx.channel().id().asLongText());
System.out.println("handlerAdded 被调用" + ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved 被调用"+ ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("异常发生 "+ cause.getMessage());
ctx.close();
}
}
消息接受的简单前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var socket;
// 判断当前浏览器是否支持webSocket
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:7000/xxx");
socket.onmessage = function (ev) {
let rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + ev.data;
}
socket.onopen = function (ev) {
let rt = document.getElementById("responseText");
rt.value = "连接开启了..."
}
socket.onclose = function (ev) {
let rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "连接关闭了..."
}
} else {
alert("当前窗口不支持webSocket")
}
function send(msg){
// webSocket是否创建好了
if (!window.socket){
return;
}
if (socket.readyState === WebSocket.OPEN){
socket.send(msg);
}else{
alert("连接未开启")
}
}
</script>
<body>
<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>