package com.fan3cn.netty;
import java.net.InetSocketAddress;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TestDemo {
//端口号
private static int port = 7777;
public static void main(String[] args) {
// TODO Auto-generated method stub
TestDemo testDemo = new TestDemo();
testDemo.startup();
}
public void startup(){
ServerBootstrap sb = new ServerBootstrap();
sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
sb.channel(NioServerSocketChannel.class);
sb.childHandler(new MySimpleChannelInboundHandler());
ChannelFuture future = sb.bind(new InetSocketAddress(port));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
// TODO Auto-generated method stub
if(f.isSuccess()){
System.out.println("bind success,listening on "+port);
}else{
System.out.println("bind failed");
}
}
});
}
/**
* handler
* @author Eric
*
*/
public class MySimpleChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf data) throws Exception {
// TODO Auto-generated method stub
int readIdx = data.readableBytes();
byte[] bytes = data.readBytes(readIdx).array();
String msg = new String(bytes);
System.out.println("recevied data:\n"+msg);
}
}
}