1. 实现功能
双向通信,客户端向服务器发送什么,服务器就向客户端发送什么
2. 服务器代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.nio.charset.Charset;
public class DoubleServer {
public static void main(String[] args) {
new ServerBootstrap()
.group(new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
/**
* 客户端有数据发来时执行此handler.
* */
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//直接拿到客户端发来的数据。
ByteBuf buffer = (ByteBuf) msg;
System.out.println(buffer.toString(Charset.defaultCharset()));
/**
* 建议使用 ctx.alloc() 创建 ByteBuf
* 将客户端发来的消息转换为ButeBuf向客户端写回去
*/
ByteBuf response = ctx.alloc().buffer();
response.writeBytes(buffer);
/**
* 向服务器写。也可以调用channel()先获取channel然后写
* Channel channel = ctx.channel();
* channel.writeAndFlush(response);
*/
ctx.writeAndFlush(response);
}
});
}
}).bind(8080);
}
}
3. 客户端代码
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
import java.util.Scanner;
public class DoubleClient {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
Channel channel = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder());
/*
* 收到服务器的数据时执行此方法
* */
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//由于服务器传输的是一个ByteBuf,这里直接强转
ByteBuf buffer = (ByteBuf) msg;
System.out.println(buffer.toString(Charset.defaultCharset()));
}
});
}
}).connect("127.0.0.1", 8080).sync().channel();
/*
* 一旦channle调用close()方法,执行这里的逻辑
* 异步回调关闭连接后,关闭线程池组。
* */
channel.closeFuture().addListener(future -> {
group.shutdownGracefully();
});
/*
* 控制台输入,然后调用writeAndFlush向服务器传输数据
* */
new Thread(() -> {
Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
if ("q".equals(line)) {
channel.close();
break;
}
//向服务器写
channel.writeAndFlush(line);
}
}).start();
}
}