那么Netty到底是何方神圣?
下面是我总结的使用Netty不使用JDK原生NIO的原因
引入Netty
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha1</version>
</dependency>
初始化代码
private static void initWebScoket() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup wokerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
.group(bossGroup, wokerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//websocket协议本身是基于http协议的,所以这边也要使用http解编码器
pipeline.addLast(new HttpServerCodec());
//以块的方式来写的处理器
pipeline.addLast(new ChunkedWriteHandler());
//netty是基于分段请求的,HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
pipeline.addLast(new HttpObjectAggregator(1024 * 1024 * 1024));
//ws://localhost:8899/ws
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
//websocket定义了传递数据的6中frame类型
pipeline.addLast(new WebSocketHandle());
}
});
ChannelFuture channelFuture = serverBootstrap
.bind(new InetSocketAddress(8899))
.sync();
channelFuture
.channel()
.closeFuture()
.sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
wokerGroup.shutdownGracefully();
}
}
bossGroup
对应接受新连接线程,主要负责创建新连接wokerGroup
对应负责读取数据的线程,主要用于读取数据以及业务逻辑处理WebSocketHandle
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
public class WebSocketHandle extends SimpleChannelInboundHandler<Object> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("用户连接");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("用户断开");
}
@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof TextWebSocketFrame) {
String receive_msg = ((TextWebSocketFrame) msg).text();
System.out.println("收到消息:" + receive_msg);
String send_msg = "服务器返回:" + receive_msg;
System.out.println("ctx.channel.id:"+ctx.channel().id());
//服务端返回消息
ctx.channel().writeAndFlush(new TextWebSocketFrame(send_msg));
} else if (msg instanceof BinaryWebSocketFrame) {
System.out.println("收到二进制消息:" + ((BinaryWebSocketFrame) msg).content().readableBytes());
BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(Unpooled.buffer().writeBytes("xxx".getBytes()));
ctx.channel().writeAndFlush(binaryWebSocketFrame);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
这样在JS中既可以这样连接
var socket = new WebSocket("ws://127.0.0.1:8899/ws");
socket.onopen = function () {
};
socket.onmessage = function (evt) {
};
socket.onclose = function (evt) {
}
socket.onerror = function (evt) {
}