服务器端代码如下:
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>() {
@Override
protected 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;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("这是第"+currentClientIndex+"个连接");
}
@Override
public 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());//指定handler
bootstrap.group(new NioEventLoopGroup());//指定与服务器端通信的
bootstrap.connect(new InetSocketAddress("localhost",10086));//连接地址和端口
}
private static class HelloClientHandler extends ChannelInboundHandlerAdapter
{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println("连通了,我打印");
}
}
}