package com.sunline.core.mktinfo.util;
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 void bind(int port) throws Exception{
//链接 connection
EventLoopGroup bossGroup=new NioEventLoopGroup();
//实际上就是读写
EventLoopGroup workerGroup=new NioEventLoopGroup();
try{
//引入辅助启动类 Builder模式
ServerBootstrap bootstarp=new ServerBootstrap();
bootstarp.group(bossGroup,workerGroup)
//创建一个服务管道类型,工厂模式 建立实例
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChildChannelHandler());
//JDK自带 异步操作调用的
ChannelFuture future=bootstarp.bind(port).sync();
future.channel().closeFuture().sync();
}catch(Exception ce){
ce.printStackTrace();
}finally{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel ch) {
// 实际业务处理类
ch.pipeline().addLast(new TimerServerHandler());
}
}
public static void main(String[] args) {
try {
int port = 8080;
TimeServer time=new TimeServer();
time.bind(port);
} catch (Exception ce) {
ce.printStackTrace();
}
}
}
//实际处理类
package com.sunline.core.mktinfo.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimerServerHandler extends ChannelHandlerAdapter{
//读取客户端传入消息
public void channelRead(ChannelHandlerContext ctx,Object msg)throws Exception{
ByteBuf buf=(ByteBuf)msg;
byte[] req=new byte[buf.readableBytes()];
String body=new String(req,"utf-8");
System.out.println("服务器接收到的消息是:"+body);
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String curtime= "QUERY_TIME_ORDER".equalsIgnoreCase(body)?df.format(new Date (System.currentTimeMillis()).toString()):"BAD_REQUEST";
//高效构建ByteFuf
ByteBuf responseBuf=Unpooled.copiedBuffer(curtime.getBytes());
ctx.write(responseBuf);
}
public void channelReadComplete(ChannelHandlerContext ctx)throws Exception{
//将缓存区中的消息全部写入socketChannel 发送给客户端
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
}