我正在写TCP上运行的自定义协议搜索服务。使用EmbeddedChannel进行测试时,一切正常。为了进一步测试,我编写了一个服务器并添加了处理程序。通过普通的Java Socket客户端的请求,服务器接收到数据,处理并发回响应。但是,响应没有到达客户端套接字。我想可能是我已经搞乱了大通道管道。所以我只将实现简化为一个入站处理程序。仍然不起作用。有人可以帮忙吗?简单的Netty服务器不发送响应
服务器:
public void start() throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
final KaiExceptionHandler kaiExceptionHandler = new KaiExceptionHandler();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new SimpleHandler());
}
});
ChannelFuture future = b.bind(new InetSocketAddress("localhost", 9400)).sync();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if(channelFuture.isSuccess()) {
LOGGER.info("Kai Server is bounded to '{}'", "localhost:9400");
}else {
LOGGER.error("Failed to bound Kai to 'localhost:9400'", channelFuture.cause());
}
}
});
future.channel().closeFuture().sync();
}finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
简单的处理器:
public class SimpleHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Charset charset = Charset.defaultCharset();
ctx.write(Unpooled.copiedBuffer("Client is not seeing this", charset));
ctx.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} }
测试客户端。一个不太整洁的实现。但是,只是为了测试。
public class TestClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 9400);
InputStream is = socket.getInputStream();
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[64];
int r = 0;
socket.setSoTimeout(10000);
System.out.println("Reading...");
while ((r = is.read(buffer)) != -1) {
sb.append(new String(buffer).trim());
}
System.out.println("String: " + sb.toString());
}
}
我明白了。如果服务器关闭套接字,'read(buffer)!= -1'成立。但是,我不希望这样的协议是基于二进制的。请求和响应以二进制形式发送,固定头大小为17字节,可选体也是二进制形式。当我知道从头部读取的确切响应体大小时,是否需要分隔符?如果是,如何? –