NettyClientHandler extends ChannelInboundHandlerAdapter 向服务端发布消息 的 demo
时间: 2024-02-02 11:05:04 浏览: 22
好的,下面是一个简单的 Netty 客户端示例代码,可以向服务端发送消息:
```java
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
private ChannelHandlerContext ctx;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
}
public void sendMessage(String message) {
ByteBuf buf = Unpooled.copiedBuffer(message, CharsetUtil.UTF_8);
ctx.writeAndFlush(buf);
}
@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();
}
}
```
在上面的代码中,重写了 `channelActive()` 方法,保存了 `ChannelHandlerContext` 对象,这样就可以在之后的代码中使用该对象发送消息。
`sendMessage()` 方法中,使用 `Unpooled.copiedBuffer()` 方法创建了一个 `ByteBuf` 对象,将消息写入该对象,并通过 `ctx.writeAndFlush()` 方法将消息发送到服务端。
`channelRead()` 方法中,接收服务端的响应,并将响应内容打印出来。
`exceptionCaught()` 方法中,处理异常并关闭连接。
需要注意的是,在使用该客户端的时候,需要先启动服务端,并确保客户端与服务端已建立连接。