Netty学习(六)—WebSocket通信
WebSocket是一种将Socket套接字引入到B/S架构中,使浏览器和服务器之间可以通过套接字建立持久连接,双方都能发送即时消息给对方,而不是传统模式下请求应答通信方式;
个人主页:tuzhenyu’s page
原文地址:Netty学习(六)—WebSocket通信
(0) 原理
HTTP协议的弊端
HTTP协议是一种被动的半双工的通信协议,也就是说同一时刻只有一个方向的数据传输;半双工的原因是通信模式采用的传统的客户端主导的请求—应答模式,只有客户端发送请求服务端才能发动应答,而服务端不能主动发送应答消息;
HTTP协议下每进行一次请求—应答通信都需要创建一次TCP连接,HTTP1,1对HTTP1.0进行改进,增添了keep-alive功能,也就是在一次TCP连接下进行多次请求—应答通信,但是通信仍然采用冗长的HTTP消息格式;
HTTP协议消息冗长,因为一个完整的HTTP消息包括消息头,消息体和换行符等,一条消息中的可用数据比例较低,相对于其他通信协议较为冗长;
HTTP协议被动通信的解决方案
HTTP是一种被动的单双工通信协议,只有客户端发送请求服务端才能发动应答,而服务端不能主动发送应答消息;在需要服务端主动推送数据的情况下,HTTP协议有极大的局限性能;
通过Ajax轮询的方式,通过前端Ajax技术定时发送轮询请求,比如1秒发送一次请求,服务端收到请求后立即返回,如果有数据则发送响应数据;
通过长轮询long poll的方式,发送请求后保持连接直到服务端有响应数据返回,客户端收到数据后再次发起long poll长轮询;
通过WebSocket方式,建立WebSocket连接后进行即时的全双工的通信;
WebSocket协议
WebSocket协议是HTML5中提出的一种全双工的持久连接的通信协议,通过HTTP协议握手建立连接后双方可以进行即时的全双工通信;
WebSocket是基于HTTP协议的,借用了HTTP的协议来完成一部分握手,完成握手后直接进行Socket通信;
WebSocket协议的优势
持久的TCP连接,无论是ajax轮询还是long poll长轮询都是不断的创建新TCP连接,频繁的连接创建和断开极大消耗资源;WebSocket通过HTTP协议完成握手建立连接后,通过该TCP连接进行双向的通信无需重复创建连接;
WebSocket建立连接后的双向通信不再使用HTTP消息格式,没有附加的消息头,身份验证等
WebSocket是一种全双工的通信协议,服务端可以主动发送消息给客户端,不再需要客户端轮询;
(1) WebSocket实例
客户端
创建WebSocket连接需要发送特定的HTTP消息,普通浏览器访问无法实现需要在JS脚本里创建连接
通过new WebSocket()方法创建WebSocket连接
回调判断连接状态触发相应事件,包括连接建立事件,关闭事件,消息接收事件等
var socket;
if (!window.WebSocket){
window.WebSocket = window.MozWebSocket;
}
if(window.WebSocket){
socket = new WebSocket("ws://localhost:8000");
socket.onmessage = function (event) {
var ta = document.getElementById('responseText');
ta.value = "";
ta.value = event.data;
};
socket.onopen = function (event) {
var ta = document.getElementById('responseText');
ta.value = "打开WebSocket正常";
};
socket.onclose = function (event) {
var ta = document.getElementById('responseText');
ta.value = "";
ta.value = "WebSocket关闭";
}
}else {
alert("抱歉,您的浏览器不支持WebSocket协议");
}
发送WebSocket的消息
- 连接创建完成后,直接发送webSocekt消息
function send(message) {
if(!window.WebSocket)
return;
if (socket.readyState == WebSocket.OPEN){
console.log("send the massage");
socket.send(message);
}
else
alert("WebSocket 连接没有建立成功");
}
服务端
- 使用Netty创建服务端,往ChannelPipeline管道中添加相应的Handler添加相应的Handler处理器
public void run(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("http-codec", new HttpServerCodec());
pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
pipeline.addLast("http-chunked",new ChunkedWriteHandler());
pipeline.addLast("handler", new WebSocketServerHandler());
}
});
Channel ch = b.bind(port).sync().channel();
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
消息经过管道传递到自定义的处理器WebSocketServerHander中
- 调用channelRead()方法判断传入的消息类型,分为传统HTTP消息和WebSocket消息
public void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg); // 传统的HTTP接入
}else if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg); // WebSocket接入
}
}
- 对于传统的HTTP进行WebSocket连接握手处理
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) throws Exception {
// 如果HTTP解码失败,返回HHTP异常
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
BAD_REQUEST));
return;
}
// 构造握手响应返回,本机测试
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:8080/websocket", null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
- 对于WebSocket消息,对其指令类型判断后进行处理,WebSocket消息类型分为:关闭连接指令,Ping心跳消息和普通消息等;
private void handleWebSocketFrame(ChannelHandlerContext ctx,
WebSocketFrame frame) {
// 判断是否是关闭链路的指令
if (frame instanceof CloseWebSocketFrame) {
handshaker.close(ctx.channel(),
(CloseWebSocketFrame) frame.retain());
return;
}
// 判断是否是Ping消息
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(
new PongWebSocketFrame(frame.content().retain()));
return;
}
// 本例程仅支持文本消息,不支持二进制消息
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format(
"%s frame types not supported", frame.getClass().getName()));
}
// 返回应答消息
String request = ((TextWebSocketFrame) frame).text();
if (!"start".equals(request)){
stop = true;
System.out.println("stop");
}
if (logger.isLoggable(Level.FINE)) {
logger.fine(String.format("%s received %s", ctx.channel(), request));
}
while (!stop){
try{
ctx.channel().writeAndFlush(
new TextWebSocketFrame("欢迎使用Netty WebSocket服务,现在时刻:"
+ new java.util.Date().toString()));
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
总结
- WebSocket通信是一种对HTTP长连接keep-alive的一种改进,通过HTTP协议完成握手连接后能够进行双向即时通信,无需重复创建TCP连接并且服务端能够主动的发送消息;