Desire
Desire

Reputation: 593

Netty Server events

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

Answers (2)

johnstlr
johnstlr

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

  • Use readableBytes() to determine the number of readable bytes, and then use getByte(index) to retrieve bytes without altering the read index.
  • use markReaderIndex and resetReaderIndex before and after reading the bytes in your loop
  • use buffer.duplicate to get a buffer that shares the underlying data but manages separeat read / write indexes.

See ChannelBuffer for more information (Netty 3).

Upvotes: 0

Veebs
Veebs

Reputation: 2388

Here is an example Chat App for netty3 and netty4.

Also, for a chat client, you seem to be using server side classes: NioServerSocketChannelFactory. I think you need NioClientSocketChannelFactory.

Upvotes: 1

Related Questions