【发布时间】:2017-08-21 06:50:49
【问题描述】:
我正在编写在 TCP 上运行的自定义协议搜索服务。使用 EmbeddedChannel 进行测试时一切正常。为了进一步测试,我编写了一个服务器并添加了处理程序。通过来自普通 java Socket 客户端的请求,服务器接收数据、处理并发送回响应。但是,响应没有到达客户端套接字。我想可能是我搞砸了大通道管道。所以我将实现减少到一个入站处理程序。还是不行。有人可以在这里帮忙吗?
服务器:
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());
}
}
【问题讨论】:
标签: netty