Server伺服器
public class Server {
public static void main(String[] args){
//1.建立兩個執行緒組
//用於處理伺服器端接收客戶端連線
NioEventLoopGroup pGroup = new NioEventLoopGroup();
//用於進行網路通訊
NioEventLoopGroup cGroup = new NioEventLoopGroup();
try {
//2.建立輔助工具類,用於伺服器通道的配置
ServerBootstrap b = new ServerBootstrap();
//繫結兩個執行緒組
b.group(pGroup, cGroup)
//指定NIO模式
.channel(NioServerSocketChannel.class)
//設定tcp緩衝區佇列
.option(ChannelOption.SO_BACKLOG, 1024)
//設定傳送緩衝大小
.option(ChannelOption.SO_SNDBUF, 32 * 1024)
//設定接收緩衝大小
.option(ChannelOption.SO_RCVBUF, 32 * 1024)
//保持連線
.option(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//3.配置接收方法的處理
sc.pipeline().addLast(new ServerHandler());
}
});
//繫結埠號
b.bind(3333).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();
}
}
}
伺服器資訊處理
class ServerHandler extends ChannelInboundHandlerAdapter{
public static ArrayList<ChannelHandlerContext> channelHandlerContexts = new ArrayList<>();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(!channelHandlerContexts.contains(ctx))
{
channelHandlerContexts.add(ctx);
}
//讀取msg資訊 並且寫回給客戶端
ByteBuf buf = (ByteBuf) msg ;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req,"utf-8");
String response = "返回給客戶端的響應: " + body;
System.out.println("Server: " + body);
//寫回響應
for (ChannelHandlerContext ctx1:channelHandlerContexts ) {
if(!ctx1.equals(ctx))
{
ctx1.writeAndFlush(
// 建立一個新的big-endian緩衝區,其內容是指定array編碼的指定子區域charset。
Unpooled.copiedBuffer(response.getBytes())
);
}
}
}
客戶端
public class Client {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture cf = b.connect("127.0.0.1", 3333).sync();
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
cf.channel().writeAndFlush(Unpooled.wrappedBuffer( scanner.nextLine().getBytes()));
}
// 等待客戶端埠號關閉
cf.channel().closeFuture().sync();
group.shutdownGracefully();
}
}
客戶端處理資訊
class ClientHandler extends SimpleChannelInboundHandler{
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
System.out.println("client: " + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
}