Netty 客户端和服务端发送与接受消息

17 篇文章 0 订阅
17 篇文章 4 订阅

刚好翻以前拍的照片,今天就发几张去朋友家撸猫拍的照片吧。

 

                                                                    微信公众号

                                              王皓的GitHub:https://github.com/TenaciousDWang    

 

        继续做一个客户端与服务端收发消息的功能,首先来创建两个COMMAND指令名称。

 

 

MESSAGE_REQUEST对应客户端发送消息请求,MESSAGE_RESPONSE对应服务端响应消息请求,相应的我们来创建两个数据包对象MessageRequestPacket与MessageResponsePacket。

 

 

        接下来,我们来判断客户端是否登录成功,之前我们知道可以给Channel绑定属性,那么我们可以在客户端登陆成功后,为该连接的Channel绑定,先创建一个标志位对象。

 

 

          接下来,将登录成功与判断是否登陆成功抽取出一个工具类。

 

 

        最后在客户端收到服务端发来的登录成功相应后设置登陆成功标志位。

 

        

        接下来改造一下客户端,写一个线程用来监控控制台输入数据,一旦有数据输入就编码并发送。

 

 

        然后我们来改造客户端的逻辑处理器,添加数据包类型判断,对应不同的处理逻辑,其中当判断packet类型为MessageRequestPacket时,我们读取message数据打印在控制台上,并创建MessageResponsePacket,填充数据,编码后放入ByteBuf中发送至客户端。

 

 

        最后我们来改造客户端逻辑处理器,同客户端逻辑处理器改造,我们同样需要添加对于数据包类型的判断,来对应不同的处理逻辑,这里我们添加对于MessageResponsePacket类型数据包的判断,如果为此类型,则读取message打印至控制台。

 

 

        以上就是今天实现的客户端与服务端收发消息的功能。

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Netty 客户端服务端示例代码,可以相互发送消息服务端代码: ```java public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收客户端消息 ByteBuf buf = (ByteBuf) msg; String request = buf.toString(CharsetUtil.UTF_8); System.out.println("Client request: " + request); // 向客户端发送响应消息 String response = "Hello, Client!"; ByteBuf respBuf = Unpooled.copiedBuffer(response, CharsetUtil.UTF_8); ctx.writeAndFlush(respBuf); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 客户端代码: ```java public class NettyClientHandler extends ChannelOutboundHandlerAdapter { private ChannelHandlerContext ctx; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { // 向服务器发送消息 ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收服务端的响应 ByteBuf buf = (ByteBuf) msg; String response = buf.toString(CharsetUtil.UTF_8); System.out.println("Server response: " + response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 启动代码: ```java public class NettyDemo { public static void main(String[] args) throws InterruptedException { // 创建 EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { // 创建 ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); // 配置 ServerBootstrap serverBootstrap.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(8888)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }); // 启动服务端 ChannelFuture serverFuture = serverBootstrap.bind().sync(); // 创建 Bootstrap Bootstrap clientBootstrap = new Bootstrap(); // 配置 Bootstrap clientBootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress("localhost", 8888)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyClientHandler()); } }); // 启动客户端 ChannelFuture clientFuture = clientBootstrap.connect().sync(); // 客户端向服务器发送消息 NettyClientHandler clientHandler = (NettyClientHandler) clientFuture.channel().pipeline().last(); clientHandler.write("Hello, Server!"); // 关闭客户端服务端 clientFuture.channel().closeFuture().sync(); serverFuture.channel().closeFuture().sync(); } finally { // 释放资源 group.shutdownGracefully().sync(); } } } ``` 在上面的代码中,服务端使用 `ChannelInboundHandlerAdapter` 处理客户端的请求,客户端使用 `ChannelOutboundHandlerAdapter` 向服务端发送请求。在启动代码中,先启动服务端,再启动客户端,并使用 `ChannelFuture` 对象获取客户端的 `NettyClientHandler` 对象,通过该对象向服务端发送消息。需要注意的是,客户端服务端都需要使用同一个 `EventLoopGroup`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值