Netty actual combat-Object codec, Netty object Network transmission

Source: Internet
Author: User

Recommended Books:

Instance code: http://download.csdn.net/detail/jiangtao_st/7677503

  1. Server-side code
    <span style= "FONT-SIZE:12PX;" >/** * * <p> * Netty Server Simple * </p> * * linebasedframedecoder + message line break * * @author Check Inn HK * @ creation time: 201 4 year July 7 * @version: V1.0 */public class Nettyserver {private final int port = 8989; @Testpublic void Nettyserver () {EventLoop Group Bossgroup = new Nioeventloopgroup (); Eventloopgroup Workergroup = new Nioeventloopgroup (); try {serverbootstrap serverbootstrap = new Serverbootstrap (); Serverbootstrap.group (Bossgroup,workergroup). Channel (nioserversocketchannel.class). Option (Channeloption.so_ BACKLOG, 1024x768). Childhandler (New Childchannelhandler ());//Bind port, synchronous wait channelfuture futrue = serverbootstrap.bind (port) . sync ();//wait for the service listener port to close Futrue.channel (). Closefuture (). sync (); catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally{//exit, release thread and other related resources bossgroup.shutdowngracefully (); workergroup.shutdowngracefully ();}} Private class Childchannelhandler extends channelinitializer<socketchannel>{@Overrideprotected void INITCHannel (Socketchannel ch) throws Exception {//ch.pipeline (). AddLast (New Linebasedframedecoder (1024x768));////bytebuf delimiter = Unpooled.copiedbuffer ("$_". GetBytes ());//ch.pipeline (). AddLast (New Delimiterbasedframedecoder (2048, delimiter));////ch.pipeline (). AddLast (new Fixedlengthframedecoder); Ch.pipeline (). AddLast (New Objectdecoder ( 1024*1024,classresolvers.weakcachingconcurrentresolver (This.getclass (). getClassLoader ()))); Ch.pipeline (). AddLast (New Objectencoder ()), Ch.pipeline (). AddLast (New Stringdecoder ()); Ch.pipeline (). AddLast (New Userrespserverhandler ());}}} </span>
  2. client-side code
    <span style= "FONT-SIZE:12PX;" >/** * * <p> * nettyclient Implementation * </p> * * @author Check Inn HK * @ creation Time: July 7, 2014 * @version: V1.0 */public class Ne ttyclient {public void connect (int port,string host) {Eventloopgroup group = new Nioeventloopgroup (); try {Bootstrap bootst Rap = new Bootstrap (); Bootstrap.group (group). Channel (niosocketchannel.class). Option (Channeloption.tcp_nodelay, true). Handler (new channelinitializer<socketchannel> () {@Overrideprotected void Initchannel (Socketchannel ch) Throws Exception {Ch.pipeline (). AddLast (New Objectdecoder (1024,classresolvers.weakcachingconcurrentresolver ( This.getclass (). getClassLoader ())), Ch.pipeline (). AddLast (New Objectencoder ()); Ch.pipeline (). AddLast (New Stringdecoder ()); Ch.pipeline (). AddLast (New Userqueryclienthandler ());}); /initiates an asynchronous link operation channelfuture channelfuture = Bootstrap.connect (host, port). sync (); Channelfuture.channel (). Closefuture (). Sync ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{//off, releasing thread resources group.shutdowngracefully ();}} @Testpublic void Nettyclient () {new Nettyclient (). Connect (8989, "localhost");}} </span>
  3. ServerHander code
    <span style= "FONT-SIZE:12PX;" >/** * * <p> * User Query return * </p> * * @author Check Inn HK * @ creation Time: July 7, 2014 * @version: V1.0 */public class Userrespse Rverhandler extends Channelinboundhandleradapter {@Overridepublic void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {userquery userquery = (userquery) msg; System.out.println ("Received query request from client:" + string.valueof (userquery)); if (userquery! = null && Userquery.getuserid ( )! = 0) {Userdo Userdo = Getuserbyid (Userquery.getuserid ()); Ctx.writeandflush (Userdo);}} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {System.out.println ( "Server has Exception," + cause.getcause ());} Private Userdo Getuserbyid (int userid) {if (userid% 2 = = 0) {Userdo Zhuoxuan = new Userdo (); Zhuoxuan.setuserid (userid); Zhuo Xuan.setsex (1); Zhuoxuan.setuname ("Check Inn HK"); Zhuoxuan.setunick ("Zhuoxuan"); Zhuoxuan.setemail ("[email protected] "); return Zhuoxuan;} Else{userdo Zhuoxuan = new Userdo (); Zhuoxuan.setuserid(userId); Zhuoxuan.setsex (1); Zhuoxuan.setuname ("Zhang San"); Zhuoxuan.setunick ("Zhangsan"); Zhuoxuan.setemail ("[Email  protected] "); return Zhuoxuan;}}} </span><strong style= "FONT-SIZE:14PX;" ></strong>

  4. Clienthander Code

<span style= "font-size:12px;" >/** * * <p> * User Enquiry Request Handler * </p> * * @author Check Inn HK * @ creation Time: July 7, 2014 * @version: V1.0 */public class use Rqueryclienthandler extends Channelinboundhandleradapter {public userqueryclienthandler () {} @Overridepublic void Channelactive (Channelhandlercontext ctx) throws Exception {for (int i = 0; i <, i++) {userquery userquery = new Use Rquery (); Userquery.setuserid (1001+i); Ctx.write (userquery);} Ctx.flush ();} @Overridepublic void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {String message = string.valueof (msg); SYSTEM.OUT.PRINTLN ("netty-client:receive message," + message);} @Overridepublic void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {Ctx.flush ();} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {System.out.println ( "Client has Exception," + cause.getcause ());}} </span> 

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.