netty 多端口多协议
netty监听多个端口(9090,9091),不同端口处理不同协议(TCP,HTTP)等
启动监听
public class Main {
public static void main(String[] args) throws Exception {
TCPServer server = new TCPServer(9090,9091);
server.start();
}
}
public class TCPServer {
int tcp_port ;
int http_port;
public TCPServer(int tcp_port,int http_port){
this.tcp_port = tcp_port;
this.http_port = http_port;
}
public void start() throws Exception{
ServerBootstrap bootstrap = new ServerBootstrap();
EventLoopGroup boss = new NioEventLoopGroup(2);
EventLoopGroup work = new NioEventLoopGroup(8);
bootstrap.group(boss,work)
.handler(new LoggingHandler(LogLevel.DEBUG))
.channel(NioServerSocketChannel.class)
.childHandler(new TCPServerInitializer());
ChannelFuture f = bootstrap.bind(new InetSocketAddress(tcp_port)).sync();
ChannelFuture f1 = bootstrap.bind(new InetSocketAddress(http_port)).sync();
System.out.println(" server start up on port : " + tcp_port);
System.out.println(" server start up on port : " + http_port);
f.channel().closeFuture().sync();
f1.channel().closeFuture().sync();
}
}
public class TCPServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
InetSocketAddress socketaddr = channel.localAddress();
int port = socketaddr.getPort();
if (port == 9090){
System.out.println("端口9090");
pipeline.addLast(new LengthFieldBasedFrameDecoder(4096,0,2,0,2));
pipeline.addLast(new TCPRequestHandler());// 请求TCP处理器
}else
{
System.out.println("端口9091");
pipeline.addLast(new HttpServerCodec());// http 编解码
pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器 512*1024为接收的最大contentlength
pipeline.addLast(new HttpRequestHandler());// 请求HTP处理器
}
}
}
思路如上
public class TCPRequestHandler extends SimpleChannelInboundHandler {
private static byte[] isoMacKey = StringUtil.hexStr2Bytes("1111111111111111");
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msgIn) throws Exception {
ByteBuf buf=(ByteBuf) msgIn;
byte[] req=new byte[buf.readableBytes()];
int reqLen = buf.readableBytes();
buf.readBytes(req);
if(req[0]!=0x60){
return ;
}
System.out.println("服务器端接收的消息["+ HexUtil.toHex(req)+"]");
}
}