太和网站建设,做二手元器件那个网站查价格,网站建设的词,什么网站做ppt赚钱调用注意#xff1a;
1、端口一定要是可以访问的。
2、依赖必须注意和其他版本冲突#xff0c;比如redis的springboot starter包#xff0c;会与5.0版本冲突。 netty.version4.1.74.Final/netty.version
dependencygroupIdio…调用注意
1、端口一定要是可以访问的。
2、依赖必须注意和其他版本冲突比如redis的springboot starter包会与5.0版本冲突。 netty.version4.1.74.Final/netty.version
dependencygroupIdio.netty/groupIdartifactIdnetty-all/artifactIdversion${netty.version}/version
/dependency 首先创建socket服务 Component
Slf4j
public class NettyWebSocketServer extends Thread {public static String MsgCode GBK;public Integer port8099;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 ChannelInitializerSocketChannel {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 SimpleChannelInboundHandlerTextWebSocketFrame {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