Demos of Netty 4.x User Guide 《Netty 4.x 用户指南》中文翻译,文中用到的例子源码
https://github.com/waylau/netty-4-user-guide-demos
一 基于netty实现websocketchat
启动WebsocketChatServer
输入http://localhost:8080/
再添加一个:
发送消息:
看代码前先对netty服务端架构有一个了解
代码详解:
1.创建一个开始类 ServerBootstrap b = new ServerBootstrap();
2.开始类绑定两个EventLoopGroup组,bossGroup,workerGroup
3.选择channel为NioServerSocketChannel(服务端)
4.绑定处理器(new WebsocketChatServerInitializer())
5.添加option (这个是设置ServerSocketChannel)服务端接受连接的队列长度。
6.添加childOption(SocketChannel)连接保活,TCP会主动探测空闲连接的有效性
7.当socket关闭后关闭channel和两个EventLoopGroup
[option和childOption参数设置说明]https://www.jianshu.com/p/0bff7c020af2
接着看 WebsocketChatServerInitializer类
1.先继承了ChannelInitializer<SocketChannel> 既channel初始initChannel()
在addLast里面的实现类都必须继承自ChannelHandler
在看TextWebSocketFrameHandler类
1.继承了SimpleChannelInboundHandler<TextWebSocketFrame>
2.channelRead0()这个方法可以得到channel信息判断是不是属于自己的channel
3.handlerAdded()handlerRemoved()channelActive()channelInactive()判断增加,移除,在线,离线channel,以及捕获异常channel exceptionCaught()
再看看HttpRequestHandler类
1.继承了SimpleChannelInboundHandler<FullHttpRequest>
2.设置前台页面html
再看看html中的JS
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function(event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + '\n' + event.data
};
socket.onopen = function(event) {
var ta = document.getElementById('responseText');
ta.value = "连接开启!";
};
socket.onclose = function(event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + "连接被关闭";
};
} else {
alert("你的浏览器不支持 WebSocket!");
}
function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("连接没有开启.");
}
}
</script>