首次接触之惑
知道netty是异步的io网络框架,但不知道怎么入手,本人喜欢从最基本的代码开始学习,就是实现server和client的最少太代是什么样的?
服务器的最少代码
1. HelloServer
public class {
public static void main(String[] args) {
ServerBootstrap ss = new ServerBootstrap();
//如果不设置,java.lang.IllegalStateException: group not set
ss.group(new NioEventLoopGroup());
//如果不设置,java.lang.IllegalStateException: channel or channelFactory not set
ss.channel(NioServerSocketChannel.class);
//如果不设置,java.lang.IllegalStateException: childHandler not set
ss.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HelloServerHandler());
}
});
try {
//Create a new Channel and bind it.
//Waits for this future until it is done, and rethrows the cause of the failure if this future failed.
ChannelFuture f = ss.bind(1234).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2. HelloServerHandler
HelloServerHandler的channelRead0是在接收到客户端的数据后如何处理的逻辑
public class HelloServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println("接收到客户端的数据为:" + s);
channelHandlerContext.writeAndFlush("writeAndFlush可以输入出客户端数据");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
客户端的最少代码
1. HelloClient
public class HelloClient {
public static String host = "127.0.0.1";
public static int port = 1234;
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new HelloClientHandler());
}
});
try {
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
group.shutdownGracefully();
}
}
}
2. HelloClientHandler
public class HelloClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
System.out.println("接收服务端的数据 : " + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("与服务器连接开始,可以向服务器写入数据");
//ctx.writeAndFlush("xxxx")
}
}