NIO client and Netty server instances

Source: Internet
Author: User
Tags epoll jboss

It took a week to study the NIO and Netty in Java, in fact NiO is well understood, and the C language, should know that select and Epoll,nio and select and Epoll very similar, the use of methods and solve the problem is the same.

As for Netty, have to admire the Java language Framework technology, although this framework is very difficult to study, but for the upper-level users, the use of this Netty framework, will help us solve many performance, stability problems. At the same time, the use of the framework will greatly improve the development efficiency.

Here, do not want to talk too much about NiO and netty things, all the most basic points of knowledge, are in the following learning materials. At present, I netty the framework of the study is not in-depth, I think a half-day actually can not write what has the level of the article, after further study, will learn the results again and everyone report.

Learning materials:

nio:http://www.iteye.com/magazines/132-java-nio#590

netty:http://docs.jboss.org/netty/3.1/guide/html_single/

Multithreading: http://www.cnblogs.com/dolphin0520/p/3932921.html

Here is an example of a TCP client implemented with NIO and a TCP server implemented with Netty.

The process is: client passes a, b two integers, server calculates and returns the result to the client. A thread pool is added to the server to handle the two-digit and. Of course, from a performance point of view, there is absolutely no need to do this at this time. The main consideration is that if there is a more complex operation, the typical server-side model is to pass the task into a message queue, and the backend then uses the thread pool to process the task from the message queue and return to the processing result. So the thread pool in this place can be thought of as a future extension, or it can be thought of as a decoration.

Client code

Nioclient.java

Package Nio.client.test;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.ByteBuffer; Import Java.nio.intbuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.socketchannel;import Java.util.hashmap;import Java.util.map;import Java.util.Set;public class nioclient {private final static int max_buf_size = 1024;private inetsocketaddress serveraddr;private int Clientcount;publ IC nioclient (String IP, int port, int clientcount) {this.clientcount = Clientcount;this.serveraddr = new Inetsocketaddress (IP, port);} private void Sendmessagetosrv (Socketchannel sockchnl, int clientno, int index) throws IOException {//Send data to server. .. /*bytebuffer sendbuf = bytebuffer.allocate (max_buf_size); String sendText = "Client" + Clientno + "say" + index + "\ r \ n"; Sendbuf.put (Sendtext.getbytes ()); Sendbuf.flip (); SOCKCHNL . write (SENDBUF); System.out.println (SendText); */bytebuffer sendbuf = Bytebuffer.allocate (4*4); Sendbuf.putint (ClienTNo); sendbuf.putint (index); Sendbuf.putint (Clientno); sendbuf.putint (index); Sendbuf.flip (); Sockchnl.write ( SENDBUF); String out = String.Format ("Client:%d send message, index:%d, a:%d, B:%d", Clientno, Index, CLIENTNO, index); System.out.println (out);} private void Recvmessage (Socketchannel sockchnl, int clientno) throws IOException {/*bytebuffer recvbuf = Bytebuffer.allo Cate (max_buf_size); int bytesread = Sockchnl.read (RECVBUF); while (Bytesread > 0) {recvbuf.flip ();//write mode to read mode, position to 0,//limit to positionstring Recvtext = new String (Recvbuf.array (), 0, Bytesread), Recvbuf.clear (); Clear buffer content, read mode to write mode, position to 0, limit to CapacitySystem.out.println ("Client" + Clientno + "Receive:" + recvtext); bytesread = Sockchnl.read (RECVBUF);} */bytebuffer recvbuf = bytebuffer.allocate (max_buf_size); int bytesread = Sockchnl.read (RECVBUF); while (BytesRead > 0 ) {recvbuf.flip ();//write mode to read mode, position to 0,//limit to PositioninT result = Recvbuf.getint (); Recvbuf.clear (); Clear buffer content, read mode to write mode, position to 0, limit to capacitystring out = String.Format ("Client:%d R ECV message, Result:%d ", clientno, result); System.out.println (out); bytesread = Sockchnl.read (RECVBUF);}}  public void Startnioclient () throws IOException, interruptedexception {Selector Selector = Selector.open (); for (int i = 0; i < Clientcount; i++) {Socketchannel Socketchannel = Socketchannel.open (); socketchannel.configureblocking (false); map<string, integer> clientinfo = new hashmap<string, integer> (); Clientinfo.put ("No", I); ClientInfo.put (" Index ", 0); Socketchannel.register (selector, selectionkey.op_connect, clientinfo); Socketchannel.connect ( THIS.SERVERADDR);} while (true) {int readychannels = Selector.select (); if (0 = = Readychannels) {continue;} set<selectionkey> Selectionkeys = Selector.selectedkeys (); for (Selectionkey Sk:selectionkeys) {Map ClientInfo = ( MAP) sk.attachment (); int Clientno = (integER) clientinfo.get ("no"); Socketchannel SOCKETCHNL = (socketchannel) sk.channel (); if (Sk.isconnectable ()) {while (!socketchnl.finishconnect ()) { Thread.Sleep (5);}                        if (socketchnl.isconnected ()) {System.out.println ("Connect is finish ...");    Send data to server ... sendmessagetosrv (SOCKETCHNL, Clientno,-1); Sk.interestops (Selectionkey.op_read);}}  else if (sk.isreadable ()) {//Read data from Server...recvmessage (SOCKETCHNL, Clientno);//Send data to Server...int index = (Integer) clientinfo.get ("index"), Index + = 1;sendmessagetosrv (SOCKETCHNL, Clientno, index), Clientinfo.put ("index", index);}} Selectionkeys.clear ();}} public int Getclientcount () {return clientcount;} public void Setclientcount (int clientcount) {this.clientcount = Clientcount;}}

Main.java

Package Nio.client.test;import Java.io.ioexception;public class Main {public static void main (string[] args) {System.out . println ("Clients start ......."); Nioclient client = new Nioclient ("127.0.0.1", 8080, n); try {client.startnioclient ();} catch (IOException e) {e.printst Acktrace ();} catch (Interruptedexception e) {e.printstacktrace ();}}}

Server-side code:

Nettyserver.java

Package Com.bj58.nettytest;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.channel;import Org.jboss.netty.channel.channelfactory;import Org.jboss.netty.channel.channelpipeline;import Org.jboss.netty.channel.group.channelgroup;import Org.jboss.netty.channel.group.channelgroupfuture;import Org.jboss.netty.channel.group.DefaultChannelGroup; Import Org.jboss.netty.channel.socket.nio.nioserversocketchannelfactory;public class Nettyserver {static final Channelgroup allchannels = new Defaultchannelgroup ("Time-server");p ublic static void Main (string[] args) throws    Exception {Executorservice ThreadPool = Executors.newfixedthreadpool (5); ChannelFactory factory = new Nioserversocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ()); Serverbootstrap bootstrap = new Serverbootstrap (factory); Bootstrap.setpipelinefactory (New Serverpipelinefactory (ThreadPool)); Bootstrap.setoption ("Child.tcpnodelay", true); Bootstrap.setoption (" Child.keepalive ", true); System.out.println ("Netty Server start ..."); Channel channel = Bootstrap.bind (new inetsocketaddress (8080));/*allchannels.add (channel); System.out.println ("1111111111111111111"); Thread.Sleep (2*60*1000);        System.out.println ("2222222222222222222");        Channelgroupfuture future = Allchannels.close ();        Future.awaituninterruptibly ();        Factory.releaseexternalresources (); System.out.println ("3333333333333333333"); */}}

Serverdecoder.java

Package Com.bj58.nettytest;import Java.util.arraylist;import Java.util.list;import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.handler.codec.frame.framedecoder;public Class Serverdecoder extends framedecoder{    @Override    protected Object decode (Channelhandlercontext CTX, Channel channel, Channelbuffer buffer) throws Exception {        if (buffer.readablebytes () < 8) {            return null;        }                int clientno = Buffer.readint ();        int index = Buffer.readint ();        int a = Buffer.readint ();        int b = Buffer.readint ();        list<integer> data = new arraylist<integer> ();        Data.add (CLIENTNO);        Data.add (index);        Data.add (a);        Data.add (b);                return data;}    }

Serverhandler.java

Package Com.bj58.nettytest;import Java.util.list;import Java.util.concurrent.executorservice;import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.buffer.channelbuffers;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.channel.exceptionevent;import Org.jboss.netty.channel.messageevent;import Org.jboss.netty.channel.simplechannelhandler;public class Serverhandler extends Simplechannelhandler {private    Executorservice ThreadPool;    Public Serverhandler (Executorservice threadPool) {this.threadpool = ThreadPool;        } @Override public void messagereceived (Channelhandlercontext ctx, messageevent e) throws Interruptedexception { /* * Channelbuffer BUF = (channelbuffer) e.getmessage (); byte[] des = * Buf.array ();         String recvtext = new String (DES, 0, des.length); * SYSTEM.OUT.PRINTLN (Recvtext);         Channel ch = e.getchannel ();         * Ch.write (E.getmessage ());  */              list<integer> data = (list<integer>) e.getmessage ();        Handletask ht = new Handletask (e);                Threadpool.submit (HT);        int clientno = data.get (0);        int index = data.get (1);        int a = Data.get (2);        int B = Data.get (3);        String content = String.Format ("Client:%d, index:%d, a:%d, B:%d", Clientno, Index, A, b);                SYSTEM.OUT.PRINTLN (content);        Channel ch = e.getchannel ();        Channelbuffer buf = Channelbuffers.buffer (4);        Buf.writeint (A+B);    Ch.write (BUF); } @Override public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) {e.getcause (). Printstac        Ktrace ();        Channel ch = e.getchannel ();    Ch.close ();        }}class Handletask implements Runnable {messageevent e;    Public Handletask (Messageevent e) {this.e = e;                public void Run () {list<integer> data = (list<integer>) e.getmessage (); InchT clientno = data.get (0);        int index = data.get (1);        int a = Data.get (2);        int B = Data.get (3);        String content = String.Format ("Client:%d, index:%d, a:%d, B:%d", Clientno, Index, A, b);                SYSTEM.OUT.PRINTLN (content);        Channel ch = e.getchannel ();        Channelbuffer buf = Channelbuffers.buffer (4);        Buf.writeint (A+B);    Ch.write (BUF); }}

Serverpipelinefactory.java

Package Com.bj58.nettytest;import Static Org.jboss.netty.channel.channels.pipeline;import Java.util.concurrent.executorservice;import Org.jboss.netty.channel.channelpipeline;import Org.jboss.netty.channel.channelpipelinefactory;public class Serverpipelinefactory Implements channelpipelinefactory{           private Executorservice threadPool;    Public serverpipelinefactory (Executorservice threadPool) {        this.threadpool = ThreadPool;    }        Public Channelpipeline Getpipeline () throws Exception {        Channelpipeline pipeline = Pipeline ();        Pipeline.addlast ("Framer", New Serverdecoder ());        Pipeline.addlast ("Handler", New Serverhandler (ThreadPool));        return pipeline;}    }

Code Understanding:

The client can start n TCP clients at the same time, connect a TCP server, pass A/b two numbers, and get the sum of A/b.

When the code is finished, it is found that through the Java serialization technique, it is possible to pass a Java object directly, so that the sending and receiving ends are easier to process, and the actual project is more complex than this.

Next look at the Java serialization technology, Netty How to pass the object, and Google Protobuf, give a complete example of the RPC code.




NIO client and Netty server instances

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.