Netty4.x HelloWorld

来源:互联网 发布:python编辑器 windows 编辑:程序博客网 时间:2024/05/14 16:04

服务器端代码如下:

  

package nettyStudy;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class HelloWorldServer {public static int currentIndex=1;public static void main(String[] args) {EventLoopGroup bossGroup=new NioEventLoopGroup();//接受连接请求EventLoopGroup workGroup=new NioEventLoopGroup();//单个工作try{ServerBootstrap b=new ServerBootstrap();//帮助开启一个服务器b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new HelloWorldServerHandler(currentIndex++));}}).option(ChannelOption.SO_BACKLOG, 128)//针对NioServerChannel.childOption(ChannelOption.SO_KEEPALIVE, true);//针对Channel//绑定端口接受进来的连接ChannelFuture f=b.bind(10086).sync();f.channel().closeFuture().sync();//关闭服务器}catch(Exception e){}}/** * 下面的类相当于针对单独的客户端进行处理 * @author zpc * */private static class HelloWorldServerHandler extends ChannelInboundHandlerAdapter{private int currentClientIndex;public HelloWorldServerHandler(int currentClientIndex) {this.currentClientIndex=currentClientIndex;}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("这是第"+currentClientIndex+"个连接");}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("这是第"+currentClientIndex+"个关闭");}}}
客户端代码如下:
package nettyStudy;import java.net.InetSocketAddress;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;public class HelloWorldClient {public static void main(String[] args) {Bootstrap bootstrap=new Bootstrap();//客户端启动服务器bootstrap.channel(NioSocketChannel.class);bootstrap.handler(new HelloClientHandler());//指定handlerbootstrap.group(new NioEventLoopGroup());//指定与服务器端通信的bootstrap.connect(new InetSocketAddress("localhost",10086));//连接地址和端口}private static class HelloClientHandler extends ChannelInboundHandlerAdapter{@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {// TODO Auto-generated method stubSystem.out.println("连通了,我打印");}}}

0 0
原创粉丝点击