我正在尝试在 Netty 中实现一个基本的多客户端聊天,我被困在某一点上!代码是:
public class Server {
public static void main(String[] args) throws Exception {
ChannelFactory factory =
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
return Channels.pipeline(new ServerHandler());
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress(8888));
}
}
public class ServerHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
ChannelBuffer buf = (ChannelBuffer) e.getMessage();
Channel ch=e.getChannel();
while(buf.readable()) {
System.out.println((char) buf.readByte());
System.out.flush();
}
ch.write(e.getMessage());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
Channel ch = e.getChannel();
ch.close();
}
}
我想先阅读消息然后发送/处理它!但是 messageReceived 事件中的代码不起作用,当我第一次读取然后处理消息时,但如果我先发送然后从通道缓冲区读取,它工作正常。无论如何,我首先阅读并执行一些长时间的操作,然后在完成该处理后将响应发送回客户端。我是 Java 新手,请引导我正确的方向,我也阅读了文档和一些教程,但我仍然想知道!