写一个Netty 客户端,服务端,相互发送消息使用ChannelInboundHandlerAdapter ChannelOutboundHandlerAdapter 实现
时间: 2023-07-20 07:17:00 浏览: 203
实现客户端与服务端的文件传输
5星 · 资源好评率100%
好的,下面是一个简单的 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`。
阅读全文