《Netty權威指南》(一)簡單的時間服務器P69
阿新 • • 發佈:2017-06-14
通過 adc 不一致 nios pie bound trap 記錄 esp 由於該書是基於Netty5編寫的樣例代碼,而Netty5已經被官方廢棄。目前基於推薦版的4.1.12.Final在學習過程中,可能會出現個別接口不一致的情況。所以記錄可在4.1.12下編譯通過的代碼
package net.xjdsz.n;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import
io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.Date;
/**
* Created by dingshuo on 2017/6/14.
*/
public class TimeServer {
public void bind(int port) throws Exception{
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup
workerGroup=new NioEventLoopGroup();try{
ServerBootstrap b=new ServerBootstrap();
b.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChannelInitializer
<SocketChannel>() {@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf=(ByteBuf)msg;
byte[] req=new byte[buf.readableBytes()];
buf.readBytes(req);
String body=new String(req,"UTF-8");
System.out.println("收到數據:"+body);
String currentTime=new Date(System.currentTimeMillis()).toString();
ByteBuf resp= Unpooled.copiedBuffer(currentTime.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();
}
});
}
});
//綁定端口,同步等待成功
ChannelFuture f=b.bind(port).sync();
//等待服務端監聽端口關閉
f.channel().closeFuture().sync();
}finally {
//退出,釋放資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
TimeServer timeServer=new TimeServer();
timeServer.bind(2000);
}
}
《Netty權威指南》(一)簡單的時間服務器P69