Netty WebSocket 客户端和服务端

8 篇文章 0 订阅 ¥49.90 ¥99.00

WebSocketServerProtocolHandler 服务端

WebSocketClientProtocolHandler 客户端

服务端代码

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author lixx
 * @version 1.0
 * @since 2023-05-12 15:32
 */
public class WebSocketServer {


	public static void main(String[] args) throws InterruptedException {

		ServerBootstrap serverBootstrap;

		EventLoopGroup boss = new N
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个使用 Netty 实现 WebSocket 服务端客户端的示例代码: 服务端代码: ```java public class WebSocketServer { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/chat")); pipeline.addLast(new TextWebSocketFrameHandler()); } }); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } private static class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private final List<Channel> channels = new ArrayList<>(); @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { String text = msg.text(); System.out.println("Received message: " + text); for (Channel channel : channels) { channel.writeAndFlush(new TextWebSocketFrame("Server: " + text)); } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); } } } ``` 客户端代码: ```java public class WebSocketClient { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker( new URI("ws://localhost:8080/chat"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketClientProtocolHandler(handler.handshaker())); pipeline.addLast(handler); } }); Channel channel = bootstrap.connect("localhost", 8080).sync().channel(); handler.handshakeFuture().sync(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line = reader.readLine(); if (line == null) { break; } channel.writeAndFlush(new TextWebSocketFrame(line)); } } finally { group.shutdownGracefully(); } } private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> { private final WebSocketClientHandshaker handshaker; private ChannelPromise handshakeFuture; public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; } public ChannelFuture handshakeFuture() { return handshakeFuture; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { handshakeFuture = ctx.newPromise(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { handshaker.handshake(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("WebSocket Client disconnected!"); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } TextWebSocketFrame frame = (TextWebSocketFrame) msg; System.out.println("Received message: " + frame.text()); } } } ``` 这个示例代码启动了一个 WebSocket 服务器,监听本地的 8080 端口。当有新的 WebSocket 连接建立时,服务器会将连接加入到一个列表中,当有消息发送到服务器时,服务器会将消息转发给所有连接。同时,客户端与服务器建立连接,发送消息并接收服务器返回的消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又逢乱世

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值