Netty Learning 5-netty3.x Server and client

Source: Internet
Author: User
Tags getmessage jboss
Server1

Import java.net.InetSocketAddress;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Org.jboss.netty.bootstrap.ServerBootstrap;
Import Org.jboss.netty.channel.ChannelPipeline;
Import Org.jboss.netty.channel.ChannelPipelineFactory;
Import Org.jboss.netty.channel.Channels;

Import Org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; Netty Service-side public class Server {public static void main (string[] args) {//service class Serverbootstrap bootstrap = new Se
		Rverbootstrap ();
		Boss Thread listening port, worker thread is responsible for data reading and writing Executorservice boss = Executors.newcachedthreadpool ();
		Executorservice worker = Executors.newcachedthreadpool ();
		Set up Niosocket factory Bootstrap.setfactory (New Nioserversocketchannelfactory (boss, worker)); Set up the Pipe factory bootstrap.setpipelinefactory (new Channelpipelinefactory () {@Override public channelpipeline Getpipelin
				E () throws Exception {Channelpipeline pipeline = Channels.pipeline (); Pipeline.addlast ("Hellohandler", New Hellohandler ());
			return pipeline;
		}
		});
		Bootstrap.bind (New Inetsocketaddress (10101));
	System.out.println ("Server1 start!!!");
}} import Org.jboss.netty.buffer.ChannelBuffer;
Import Org.jboss.netty.buffer.ChannelBuffers;
Import Org.jboss.netty.channel.ChannelHandlerContext;
Import org.jboss.netty.channel.ChannelStateEvent;
Import org.jboss.netty.channel.ExceptionEvent;
Import org.jboss.netty.channel.MessageEvent;

Import Org.jboss.netty.channel.SimpleChannelHandler; Message Accept processing class public class Hellohandler extends Simplechannelhandler {//Receive message @Override public void messagereceived (Chan  Nelhandlercontext CTX, Messageevent e) throws Exception {//Receive message Channelbuffer messagereceived = (channelbuffer)
		E.getmessage ();
		String messagerecstr = new String (Messagereceived.array ());

		System.out.println (MESSAGERECSTR); Writeback data if ("Hello". Equals (Messagerecstr)) {Channelbuffer Sendback = channelbuffers.copiedbuffer ("Hi". getBytes
			()); Ctx.getchanneL (). write (Sendback);
			else {Channelbuffer Sendback = channelbuffers. Copiedbuffer ("I don ' t know what you said". GetBytes ());
		Ctx.getchannel (). write (Sendback);
	} super.messagereceived (CTX, E); }//catch exception @Override public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception {S
		Ystem.out.println ("Exceptioncaught");
	Super.exceptioncaught (CTX, E);
		}//New connection @Override public void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception {
		System.out.println ("channelconnected");
	Super.channelconnected (CTX, E); @Override public void channeldisconnected (Channelhandlercontext ctx, channelstateevent e) will not be triggered until the channel is closed when the link has been established.
		Throws Exception {System.out.println ("channeldisconnected");
	Super.channeldisconnected (CTX, E); ///channel shutdown (see Client impersonation) @Override public void channelclosed (Channelhandlercontext ctx, channelstateevent e) thr oWS Exception {System.out.println ("ChannelcloseD ");
	Super.channelclosed (CTX, E); }
}


Server2 Compared to Example 1, the stringencoder and stringdecoder Two handler objects were added.
Stringdecoder decodes the accepted content and inherits the Channelupstreamhandler class. Stringencoder encodes the sent content and inherits the Channeldownstreamhandler class.
Please refer to this blog, "Netty Learning 6-source tracking Channelpipeline and Chanelhandler working principle"
http://blog.csdn.net/woshixuye/article/details/53859776

Import java.net.InetSocketAddress;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Org.jboss.netty.bootstrap.ServerBootstrap;
Import Org.jboss.netty.channel.ChannelPipeline;
Import Org.jboss.netty.channel.ChannelPipelineFactory;
Import Org.jboss.netty.channel.Channels;
Import Org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
Import Org.jboss.netty.handler.codec.string.StringDecoder;


Import Org.jboss.netty.handler.codec.string.StringEncoder; Netty Service-side entry public class Server {public static void main (string[] args) {//service class Serverbootstrap bootstrap = new
		Serverbootstrap ();
		Boss Thread listening port, worker thread is responsible for data reading and writing Executorservice boss = Executors.newcachedthreadpool ();
		Executorservice worker = Executors.newcachedthreadpool ();
		Set up Niosocket factory Bootstrap.setfactory (New Nioserversocketchannelfactory (boss, worker)); Set up the Pipe factory bootstrap.setpipelinefactory (new Channelpipelinefactory () {@Override public Channelpipeline Getpipeline () throws Exception {Channelpipeline pipeline = Channels.pipeline ();
				Pipeline.addlast ("Decoder", New Stringdecoder ());
				Pipeline.addlast ("encoder", New Stringencoder ());
				Pipeline.addlast ("Hellohandler", New Hellohandler ());
			return pipeline;
		}
		});
		Bootstrap.bind (New Inetsocketaddress (10101));
	System.out.println ("Server2 start!!!");
}} import Org.jboss.netty.channel.ChannelHandlerContext;
Import org.jboss.netty.channel.ChannelStateEvent;
Import org.jboss.netty.channel.ExceptionEvent;
Import org.jboss.netty.channel.MessageEvent;

Import Org.jboss.netty.channel.SimpleChannelHandler; Message Accept processing class public class Hellohandler extends Simplechannelhandler {//Receive message @Override public void messagereceived (Chan Nelhandlercontext CTX, Messageevent e) throws Exception {//Receive message String messagereceived = (string) e.getmessage ()
		;

		System.out.println (messagereceived);
Write back the data if ("Hello". Equals (messagereceived)) Ctx.getchannel (). Write ("Hi");		else Ctx.getchannel (). Write ("I don ' t know what you said");
	Super.messagereceived (CTX, E); }//catch exception @Override public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception {S
		Ystem.out.println ("Exceptioncaught");
	Super.exceptioncaught (CTX, E);
		}//New connection @Override public void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception {
		System.out.println ("channelconnected");
	Super.channelconnected (CTX, E); @Override public void channeldisconnected (Channelhandlercontext ctx, channelstateevent e) will not be triggered until the channel is closed when the link has been established.
		Throws Exception {System.out.println ("channeldisconnected");
	Super.channeldisconnected (CTX, E); ///channel shutdown (see Client impersonation) @Override public void channelclosed (Channelhandlercontext ctx, channelstateevent e) thr
		oWS Exception {System.out.println ("channelclosed");
	Super.channelclosed (CTX, E);
 }
}
Client
Import java.net.InetSocketAddress;
Import Java.util.Scanner;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Org.jboss.netty.bootstrap.ClientBootstrap;
Import Org.jboss.netty.channel.Channel;
Import Org.jboss.netty.channel.ChannelFuture;
Import Org.jboss.netty.channel.ChannelPipeline;
Import Org.jboss.netty.channel.ChannelPipelineFactory;
Import Org.jboss.netty.channel.Channels;
Import Org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
Import Org.jboss.netty.handler.codec.string.StringDecoder;

Import Org.jboss.netty.handler.codec.string.StringEncoder;  /** * Netty Client Entry/public class Client {@SuppressWarnings (' resource ') public static void main (string[] args) {//
		Service class Clientbootstrap bootstrap = new Clientbootstrap ();
		Thread pool Executorservice boss = Executors.newcachedthreadpool ();
		Executorservice worker = Executors.newcachedthreadpool (); Socket Factory Bootstrap.setfactory (new Nioclientsocketchannelfactory boss, Worker));  Pipe Factory Bootstrap.setpipelinefactory (new Channelpipelinefactory () {@Override public channelpipeline getpipeline ()
				Throws Exception {Channelpipeline pipeline = Channels.pipeline ();
				Pipeline.addlast ("Decoder", New Stringdecoder ());
				Pipeline.addlast ("encoder", New Stringencoder ());
				Pipeline.addlast ("Hihandler", New Hihandler ());
			return pipeline;

		}
		});
		Connect the service side channelfuture connect = bootstrap.connect (new inetsocketaddress ("127.0.0.1", 10101));
		Channel Channel = Connect.getchannel ();

		SYSTEM.OUT.PRINTLN ("client start");
		Scanner Scanner = new Scanner (system.in);
			while (true) {System.out.println ("Please enter");
		Channel.write (Scanner.next ());
}} import Org.jboss.netty.channel.ChannelHandlerContext;
Import org.jboss.netty.channel.ChannelStateEvent;
Import org.jboss.netty.channel.ExceptionEvent;
Import org.jboss.netty.channel.MessageEvent;

Import Org.jboss.netty.channel.SimpleChannelHandler; /** * Message Accept processing class * * Public clAss Hihandler extends Simplechannelhandler {//Receive message @Override public void messagereceived (Channelhandlercontext ctx,
		Messageevent e) throws Exception {//Receive message String s = (string) e.getmessage ();
		System.out.println (s);
	Super.messagereceived (CTX, E); }//catch exception @Override public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception {S
		Ystem.out.println ("Exceptioncaught");
	Super.exceptioncaught (CTX, E);
		}//New connection @Override public void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception {
		System.out.println ("channelconnected");
	Super.channelconnected (CTX, E); The @Override public void channeldisconnected (Channelhandlercontext ctx, channelstateevent, will not be triggered until the channel is closed when the connection has been established).
		E) throws Exception {System.out.println ("channeldisconnected");
	Super.channeldisconnected (CTX, E); //channel shutdown (such as the server does not start, the client initiates the connection, it will report this error) @Override public void channelclosed (Channelhandlercontext ctx, Channelstateevent e) throws Exception {System.out.println ("channelclosed");
	Super.channelclosed (CTX, E);
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.