当前位置: 首页> 科技> 名企 > Java实现通过netty建立websocket连接

Java实现通过netty建立websocket连接

时间:2025/9/12 1:50:42来源:https://blog.csdn.net/m0_48038376/article/details/141166199 浏览次数:0次

使用 Netty 建立 WebSocket 连接并区分用户

1. 添加依赖
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.63.Final</version>
</dependency>
2. 创建 WebSocket 客户端

添加了一个 userId 用来区分用户

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;public class WebSocketClient {private static final String USER_ID = "user123"; // 替换为实际的用户 IDpublic static void main(String[] args) throws Exception {NioEventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) {ch.pipeline().addLast(new HttpClientCodec());ch.pipeline().addLast(new HttpObjectAggregator(8192));ch.pipeline().addLast(new WebSocketFrameAggregator(8192));ch.pipeline().addLast(new WebSocketClientHandler(USER_ID));}});// 连接到服务器ChannelFuture future = bootstrap.connect("localhost", 8080).sync();future.channel().closeFuture().sync();} finally {group.shutdownGracefully().sync();}}private static class WebSocketClientHandler extends ChannelInboundHandlerAdapter {private final String userId;public WebSocketClientHandler(String userId) {this.userId = userId;}@Overridepublic void channelActive(ChannelHandlerContext ctx) {WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(ctx.channel().localAddress(), WebSocketVersion.V13, null, true, new DefaultHttpHeaders());handshaker.handshake(ctx.channel());}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {if (msg instanceof WebSocketFrame) {WebSocketFrame frame = (WebSocketFrame) msg;if (frame instanceof TextWebSocketFrame) {TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;String message = textFrame.text();// 处理用户消息System.out.println("用户 " + userId + " 收到消息: " + message);}}}}
}
关键字:Java实现通过netty建立websocket连接

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: