Mina, Netty, twisted learn Together (i): Implementing a Simple TCP server

Source: Internet
Author: User
Tags throwable

MINA, Netty, twisted Why do you study together? First, take a look at the introduction of their official website:

MINA:

Apache MINA is a network application framework which helps users develop high performance and high scalability NE Twork applications easily. It provides an abstract Event-driven asynchronous API over various transports such as TCP/IP and UDP/IP via Java Nio.

Netty:

Netty is a asynchronous Event-driven Network application framework for rapid development of MAINTAINABL E High Performance protocol servers & clients.

Twisted:

Twisted is a Event-driven networking engine written in Python and licensed under the Open Source MIT license.

(Twisted official website of the copy is not professional Ah, incredibly do not write asynchronous)

From the brief introduction above, we can find their common features: Event-driven and asynchronous. They are both event-driven and asynchronous network programming frameworks . This shows that the common denominator between them is still very obvious. So I'm going to put these three frames together to achieve the same functionality, not only to learn three things with a small amount of energy, but also to compare them in various ways.

Where Mina and Netty are based on the Java language, and twisted is the Python language. But language is not the focus, the focus is the idea.

When using traditional bio (Blocking io/blocking IO) for network programming, network IO reads and writes will block the current thread, and if a TCP server is implemented, one thread must be opened for each client connection, and many threads may be fooling around waiting for read and write data. System resource consumption is large.

NIO (non-blocking io/non-blocking IO) or AIO (asynchronous io/asynchronous IO) is implemented via IO multiplexing, without the need to create a thread for each connection, and its underlying implementation is through some of the features of the operating system such as SELECT, pool , Epoll, IOCP, etc., these are not the focus of this article. All three of these network frameworks are based on this implementation.

The following three frameworks are used to implement one of the simplest TCP servers. When a string that is sent to the client is received, a string is written back to the client as a response.

Mina:

 Public classTCPServer { Public Static voidMain (string[] args)throwsIOException {ioacceptor acceptor=NewNiosocketacceptor (); Acceptor.sethandler (NewTcpserverhandle ()); Acceptor.bind (NewInetsocketaddress (8080)); }    }    classTcpserverhandleextendsIohandleradapter {@Override Public voidExceptioncaught (iosession session, Throwable Cause)throwsException {cause.printstacktrace (); }        //Receive new Data@Override Public voidMessagereceived (iosession session, Object message)throwsException {//receiving data from the clientIobuffer Iobuffer =(iobuffer) message; byte[] ByteArray =New byte[Iobuffer.limit ()]; Iobuffer.get (ByteArray,0, Iobuffer.limit ()); System.out.println ("Messagereceived:" +NewString (ByteArray, "UTF-8")); //Send to client        byte[] Responsebytearray = "Hello". GetBytes ("UTF-8"); Iobuffer Responseiobuffer=iobuffer.allocate (responsebytearray.length);          Responseiobuffer.put (Responsebytearray);          Responseiobuffer.flip ();      Session.write (Responseiobuffer); } @Override Public voidSessioncreated (iosession session)throwsException {System.out.println ("Sessioncreated"); } @Override Public voidSessionclosed (iosession session)throwsException {System.out.println ("Sessionclosed"); }  }  

Netty:

 Public classTCPServer { Public Static voidMain (string[] args)throwsinterruptedexception {eventloopgroup bossgroup=NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try{Serverbootstrap b=NewServerbootstrap (); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Childhandler (NewChannelinitializer<socketchannel>() {@Override Public voidinitchannel (socketchannel ch)throwsException {ch.pipeline (). AddLast (NewTcpserverhandler ());              }                      }); Channelfuture F= B.bind (8080). sync ();          F.channel (). Closefuture (). sync (); } finally{workergroup.shutdowngracefully ();          Bossgroup.shutdowngracefully (); }      }    }    classTcpserverhandlerextendsChannelinboundhandleradapter {//Receive new Data@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsunsupportedencodingexception {Try {              //receiving data from the clientBytebuf in =(BYTEBUF) msg; System.out.println ("Channelread:" +in.tostring (charsetutil.utf_8)); //Send to client            byte[] Responsebytearray = "Hello". GetBytes ("UTF-8"); Bytebuf out=ctx.alloc (). Buffer (responsebytearray.length);              Out.writebytes (Responsebytearray);                        Ctx.writeandflush (out); } finally{referencecountutil.release (msg); }} @Override Public voidchannelactive (Channelhandlercontext ctx) {System.out.println ("Channelactive"); } @Override Public voidchannelinactive (Channelhandlercontext ctx) {System.out.println ("Channelinactive"); } @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) {cause.printstacktrace ();      Ctx.close (); }  }  

Twisted:

#-*-coding:utf-8–*-   fromTwisted.internet.protocolImportProtocol fromTwisted.internet.protocolImportFactory fromTwisted.internetImportreactorclassTcpserverhandle (Protocol):#The new connection is established    defConnectionmade (self):Print 'Connectionmade'                #Connection Disconnect    defconnectionlost (self, Reason):Print 'Connectionlost'            #Receive new Data    defdatareceived (self, data):Print 'datareceived', Data self.transport.write ('Hello') Factory=Factory () Factory.protocol=Tcpserverhandle reactor.listentcp (8080, Factory) Reactor.run ()

The above code shows that the TCP server implemented by these three frameworks will trigger an event when the connection is established, the data received from the client, and the connection is closed. For example, when you receive data from a client, Mina triggers an event call Messagereceived,netty calls Channelread,twisted calls DataReceived. When you write code, you only need to inherit a class and override the response method. This is the Event-driven event driver.

Here is a TCP client written by Java as a test, the client does not use these three frameworks, nor does it use NIO, just a regular bio of the TCP client.

TCP can send and receive data multiple times during the process of establishing a connection to a close connection. The following client sends two strings to the server and two times the data for the server response, between 5 seconds through Thread.Sleep (5000) interval.

 Public classTcpClient { Public Static voidMain (string[] args)throwsIOException, interruptedexception {socket socket=NULL; OutputStream out=NULL; InputStream in=NULL; Try{Socket=NewSocket ("localhost", 8080); out=Socket.getoutputstream (); Inch=Socket.getinputstream (); //Request ServerOut.write ("First request". GetBytes ("UTF-8")));                                    Out.flush (); //Get server response, output            byte[] ByteArray =New byte[1024]; intLength =In.read (ByteArray); System.out.println (NewString (byteArray, 0, length, "UTF-8"))); Thread.Sleep (5000); //requesting the server againOut.write ("Second Request". GetBytes ("UTF-8")));                            Out.flush (); //get the server response again, the outputByteArray =New byte[1024]; Length=In.read (ByteArray); System.out.println (NewString (byteArray, 0, length, "UTF-8"))); } finally {              //Close ConnectionIn.close ();              Out.close ();          Socket.close (); }      }  }  

Use the client to test the above three TCP servers separately:

Mina Server output results:

sessioncreated
Messagereceived: First time request
Messagereceived: Second Request
Sessionclosed

Netty Server Output results:

Channelactive
Channelread: First time request
Channelread: Second Request
Channelinactive

Twisted Server Output results:

Connectionmade
DataReceived: First time request
DataReceived: Second Request
Connectionlost

Mina, Netty, twisted learn Together (i): Implementing a Simple TCP server

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.