import java.net.InetSocketAddress; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
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; public class TimeServer { public static void main(String[] args) throws Exception{
new TimeServer().bind("192.168.1.102", 8400);
} public void bind(String addr,int port) {
//配置服务端的nio线程组
EventLoopGroup boosGroup=new NioEventLoopGroup();
EventLoopGroup workerGroup=new NioEventLoopGroup();
try {
ServerBootstrap b=new ServerBootstrap();
b.group(boosGroup,workerGroup);
b.channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChildChannelHandler());
//绑定端口,同步等待成功
ChannelFuture f=b.bind(new InetSocketAddress(addr, port)).sync();
//等等服务器端监听端口关闭
f.channel().closeFuture().sync();
} catch (Exception e) {
// TODO: handle exception
}finally{
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{ @Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler()); } } }
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class TimeServerHandler extends ChannelHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf=(ByteBuf)msg;
byte[] bytes=new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body=new String(bytes,"UTF-8");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=dateFormat.format(new Date());
String res="来自与服务端的回应,时间:"+ time;
ByteBuf resp=Unpooled.copiedBuffer(res.getBytes());
ctx.write(resp); } @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
} }
这个比传统的nio好用多了,netty的版本为netty-all-5.0.0.Alpha1.jar
天天学习,天天进步