服务器端
[Asm] 纯文本查看 复制代码 package org.example;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
public class Server {
public static void main(String[] args) {
new ServerBootstrap().group(new NioEventLoopGroup()).channel(NioServerSocketChannel.class).
childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
ChannelPipeline pipeline = nioSocketChannel.pipeline();
pipeline.addLast("h1",new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("h1");
super.channelRead(ctx, msg);
}
});
pipeline.addLast("h2",new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
System.out.println("h2");
super.write(ctx, msg, promise);
}
});
}
}).bind(8888);
}
}
客户端
[Asm] 纯文本查看 复制代码 package org.example;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
public class Client {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 当客户端连接服务器后发送消息
ctx.writeAndFlush("Hello Server!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 处理服务器发来的消息
System.out.println("Received from server: " + msg);
}
});
}
});
ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
建立链接能成功 但是客户端那边不会打印h1是怎么回事呢? |