【第4篇】Netty对WebSocket的支援分析
2019-05-13 本文已影响0人
爱学习的蹭蹭
1、WebSocket的简要描述(重点)
- WebSocket 是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。
- WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。
- 在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接(长连接),并进行双向数据传输。
- 在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
2、Netty对WebSocket的支援(重点)
- Websocket 主要的特征服务端和客户端进行建立长连接,在客户端和服务器一旦建立会基于http之上转换成socket,连接之后会是全双供通信,服务端与客户端是等价的,客户端随时可以服务器发送数据,服务端也可以向客户端发送数据,然而websocket适合做即时通信聊天
- websocket的出现弥补http1.0没办法做到的事情,同时实现H5的一部分支持
- WebSocket只传数据,本身没有http协议太多的头属性(减轻带宽流量)
- 注意点:服务端如果向客户端发生数据包时反复发生,假设通过多次进行处理,客户端还没数据响应,此时服务端就认为客户端是断开,服务端会重新建立新的Socket,在WebSocket中是极为常见的问题
4、Netty的重要的类
- ChuckedWriteHandler块处理器,Netty在处理http请求的底层是以分段/分块进行处理(难点)
- HttpObjectAggregator集合
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandler());
}
}
3、WebSocket处理要点
- WebSocketServerProtocolHandler("/ws") 指定websocket处理器,此设定是处理websocket繁重的事情
- TextWebSocketFrame专门处理文本的类
- asLongFext是长度文本唯一Id
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("收到消息: " + msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded: " + ctx.channel().id().asLongText());
}
@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("异常发生");
ctx.close();
}
}
public interface ChannelId extends Serializable, Comparable<ChannelId> {
/**
* 返回简短,但全局非惟一的字符串表示形式。
*/
String asShortText();
/**
* 返回长,但全局唯一的字符串表示形式。
*/
String asLongText();
}
WebSocketServerProtocolHandler