Package Demo;
Import java.net.InetSocketAddress;
Import java.util.concurrent.Executors;
Import Org.jboss.netty.bootstrap.ServerBootstrap;
Import Org.jboss.netty.buffer.ChannelBuffers;
Import Org.jboss.netty.channel.Channel;
Import Org.jboss.netty.channel.ChannelHandlerContext;
Import Org.jboss.netty.channel.ChannelPipeline;
Import Org.jboss.netty.channel.ChannelPipelineFactory;
Import org.jboss.netty.channel.ChannelStateEvent;
Import Org.jboss.netty.channel.Channels;
Import org.jboss.netty.channel.ExceptionEvent;
Import org.jboss.netty.channel.MessageEvent;
Import Org.jboss.netty.channel.SimpleChannelHandler;
Import Org.jboss.netty.channel.SimpleChannelUpstreamHandler;
Import Org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
Import Org.jboss.netty.handler.codec.string.StringDecoder;
public class Nioserverdemo extends Simplechannelupstreamhandler {
/**
*
* @param args
*/
public static void Main (string[] args) {
Server service Initiator
Serverbootstrap Server = new Serverbootstrap (
New Nioserversocketchannelfactory (
Executors.newcachedthreadpool (),
Executors.newcachedthreadpool ()));
Server.setpipelinefactory (New Channelpipelinefactory () {
@Override
Public Channelpipeline Getpipeline () throws Exception {
TODO auto-generated Method Stub
Channelpipeline pipeline = Channels.pipeline ();
Pipeline.addlast ("Decode", New Stringdecoder ());
Pipeline.addlast ("Encode", New Stringdecoder ());
Pipeline.addlast ("Thread", New Nioserverdemo ());
return pipeline;
}
});
Server.bind (New inetsocketaddress (8000));
SYSTEM.OUT.PRINTLN ("Service has started waiting for client connections ...");
}
@Override
public void channelconnected (Channelhandlercontext ctx, channelstateevent e) {
When there is a client connection on the server execution method
System.out.println (E.getvalue (). toString () + "The client is connected to the server!" ");
}
@Override
public void messagereceived (Channelhandlercontext ctx, messageevent e)
Throws Exception {
Receive the data from the client to process and reply to the client
SYSTEM.OUT.PRINTLN ("Client information:" + E.getchannel (). getremoteaddress ());
SYSTEM.OUT.PRINTLN ("Server information:" + E.getchannel (). getlocaladdress ());
System.out.println ("received message:" + e.getmessage (). toString ());
E.getchannel (). Write (
Channelbuffers.wrappedbuffer (E.getmessage (). ToString ()
. GetBytes ()));
}
@Override
public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) {
When the client dropped the line trigger method
SYSTEM.OUT.PRINTLN ("Client" +ctx.getchannel (). Getremoteaddress () + "is disconnected:" + ("The remote host forced the shutdown of an existing connection. "). Equals (E.getcause (). GetMessage ()));
}
}
Netty Server-side Demo