netty实现websocket通信
调用注意:
1、端口一定要是可以访问的。
2、依赖必须注意和其他版本冲突,比如redis的springboot starter包,会与5.0+版本冲突。
<netty.version>4.1.74.Final</netty.version>
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>${netty.version}</version>
</dependency>
首先创建socket服务
@Component
@Slf4j
public class NettyWebSocketServer extends Thread {public static String MsgCode = "GBK";public Integer port=8099;@Overridepublic void run() {startServer();}private void startServer() {EventLoopGroup bossGroup = null;EventLoopGroup workGroup = null;ServerBootstrap serverBootstrap = null;ChannelFuture future = null;try {//初始化线程组bossGroup = new NioEventLoopGroup();workGroup = new NioEventLoopGroup();//初始化服务端配置serverBootstrap = new ServerBootstrap();//绑定线程组serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).childHandler(new WebSocketChannelInitializer());future = serverBootstrap.bind(new InetSocketAddress(port)).sync();log.info(" *************Web Socket服务端启动成功 Port:{}*********** ", port);} catch (Exception e) {log.error("Web Socket服务端启动异常", e);} finally {if (future != null) {try {future.channel().closeFuture().sync();} catch (InterruptedException e) {log.error("channel关闭异常:", e);}}if (bossGroup != null) {//线程组资源回收bossGroup.shutdownGracefully();}if (workGroup != null) {//线程组资源回收workGroup.shutdownGracefully();}}}}
创建WebSocketChannelInitializer,配置请求目录、handle类,以及请求的最大内容
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {protected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();pipeline.addLast(new HttpServerCodec());pipeline.addLast(new ChunkedWriteHandler());pipeline.addLast(new HttpObjectAggregator(5000));pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));pipeline.addLast(new TextWebSocketFrameHandle());}
}
channelRead0方法可以处理收到的消息,并回复,如果实现聊天功能需要记录channel,然后通过channel来回复
@Slf4j
public class TextWebSocketFrameHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {log.info("收到消息:" + msg.text());ctx.channel().writeAndFlush(new TextWebSocketFrame("收到客户端消息"));}@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {log.info("handlerAdded:" +ctx.channel().id().asLongText());}@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {log.info("handlerAdded:" +ctx.channel().id().asLongText());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {log.error("异常发生");ctx.close();}
}
web调用的地址为:ws://localhost:8099/ws