我在Android 和服务器都是用的Netty框架,原来采用的都是socket通讯,现在我需要增加Http请求。参考了网上一片博文后服务端可以同时处理socket和http通讯,浏览器和socket测试过 链接:Netty如何实现同一个端口接收TCP和HTTP请求 https://my.oschina.net/succy/blog/4724766
测试结果
现在遇到问题是android 端收不到 socket和http通讯返回的数据;并且多次请求后还会报错:
rejectedExecution: Failed to submit a listener notification task. Event loop shut down?
android端netty配置如下:
EventLoopGroup loopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(loopGroup).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
//.option(ChannelOption.SO_BACKLOG, 512)
.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
.remoteAddress(new InetSocketAddress(HOST, PORT))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
ch.pipeline().addLast(new HttpRequestEncoder());
ch.pipeline().addLast(new HttpResponseDecoder());
// ch.pipeline().addLast(new ByteArrayEncoder());
ch.pipeline().addLast(new PortUnificationServerHandler());
}
});
ChannelFuture future = bootstrap.connect().sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
LogUtils.e(TAG, e.getMessage());
e.printStackTrace();
} finally {
try {
loopGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
LogUtils.e(TAG, e.getMessage());
e.printStackTrace();
}
}
PortUnificationServerHandler这个类和服务端基本一致,见上面链接中博文,我觉得客户端这样配置不对,但不知道怎么配置Netty客户端才能兼容发送Socket和Http请求。在 channelActive 等函数中都有打上日志但没有响应。