搭建服务基本配置参考第1篇。本篇仅介绍实现WebSocket服务器的关键代码
initChannel
public void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(64 * 1024)); pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));pipeline.addLast(new TextWebSocketFrameHandler()); //自定义
- HttpServerCodec和HttpObjectAggregator:是netty自带的,用于处理http请求的。我们知道WebSocket是ws请求,而不是http。而ws在第一次请求的时候,需要建立ws连接,此时是http。只有建立了ws长连接以后,后续的请求,才转变为ws通信。
- WebSocketServerProtocolHandler:参数ws,指当收到请求地址为 xxxxx/ws 时,将把当前连接转变成一个ws长连接。
- TextWebSocketFrameHandler:自定义的用于处理ws长连接的Handler,如下
WebSocketFrameHandler
public class TextWebSocketFrameHandlerextends SimpleChannelInboundHandler<TextWebSocketFrame> {@Overridepublic void channelRead0(ChannelHandlerContext ctx,TextWebSocketFrame msg) throws Exception {System.out.println("收到消息"+msg.text());ctx.writeAndFlush(new TextWebSocketFrame( "发出消息"));}
以上是收发消息的例子,相关语法如果不理解,可以看本专题的前面几篇。
运行服务器,网上找一个ws在线客户端请求 ws://xxxxxx/ws 进行测试