Reputation: 593
I'm trying to implement a basic MultiClient Chat in Netty, I'm stuck at one point! The code is:
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();
}
}
I want first to read the message & then send/process it! but the code in messageReceived Event is not working, when I first read & then process the message, but its working fine if I send first and read after from channel buffer. Is there anyway I first read and perform some long operations & then on completion of that processing I send response back to client. I'm a Java newbie, Kindly guide me in right direction, I've read the documentation & some tutorials as well, but still I'm wondering!
Upvotes: 0
Views: 657
Reputation: 1431
I suspect the problem is that reading from the buffer alters the buffer's read index. When you come to write the buffer to the channel the read index is at the end of the data. There are a few options
See ChannelBuffer for more information (Netty 3).
Upvotes: 0