Mina, Netty, twisted learn together: Implement a Simple TCP server

Source: Internet
Author: User

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 Li Cense.

(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 accepted, a string is written back to the client as a response.

Mina:

public class TCPServer {public static void main (string[] args) throws IOException {Ioacceptor acceptor = new Niosocketacce Ptor (); Acceptor.sethandler (new Tcpserverhandle ()); Acceptor.bind (new inetsocketaddress (8080));}} Class Tcpserverhandle extends Iohandleradapter {@Overridepublic void Exceptioncaught (iosession session, Throwable cause ) throws Exception {Cause.printstacktrace ();} Receive new data @overridepublic void Messagereceived (iosession session, Object message) throws Exception {//Receive client data Iobuffer I Obuffer = (iobuffer) message;byte[] ByteArray = new Byte[iobuffer.limit ()];iobuffer.get (ByteArray, 0, Iobuffer.limit ()) ; System.out.println ("messagereceived:" + new String (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);} @Overridepublic void Sessioncreated (Iosession session) throws Exception {SysteM.out.println ("sessioncreated");} @Overridepublic void Sessionclosed (Iosession session) throws Exception {System.out.println ("sessionclosed");}}

Netty:

public class TCPServer {public static void main (string[] args) throws Interruptedexception {Eventloopgroup Bossgroup = new Nioeventloopgroup (); Eventloopgroup Workergroup = new Nioeventloopgroup (); try {serverbootstrap b = new Serverbootstrap (); B.group (BossGroup, Workergroup). Channel (Nioserversocketchannel.class). Childhandler (New channelinitializer<socketchannel> () {@ overridepublic void Initchannel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Tcpserverhandler ());}}). Option (Channeloption.so_backlog, +). Childoption (Channeloption.so_keepalive, true); Channelfuture f = b.bind (8080). sync (); F.channel (). Closefuture (). sync (); finally {workergroup.shutdowngracefully (); bossgroup.shutdowngracefully ();}}} Class Tcpserverhandler extends Channelinboundhandleradapter {//Receive new data @overridepublic void Channelread ( Channelhandlercontext ctx, Object msg) throws Unsupportedencodingexception {try {//Receive client data bytebuf 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);}} @Overridepublic void Channelactive (Channelhandlercontext ctx) {System.out.println ("channelactive");} @Overridepublic void Channelinactive (Channelhandlercontext ctx) {System.out.println ("channelinactive");} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {cause.printstacktrace (); Ctx.close ( );}}

Twisted:

#-*-coding:utf-8–*-from twisted.internet.protocol import protocolfrom twisted.internet.protocol import Factoryfrom Twisted.internet Import Reactorclass Tcpserverhandle (Protocol):        # New Connection established    def connectionmade (self):        print ' Connectionmade '            # Connection Disconnect    def connectionlost (self, Reason):        print ' Connectionlost '        # received new data    def datareceived (self, data):        print ' datareceived ', Data        self.transport.write (' hello ') factory = Factory () Factory.protocol = tcpserverhandlereactor.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 class TcpClient {public static void main (string[] args) throws IOException, interruptedexception {socket socket = n Ull;outputstream out = Null;inputstream in = Null;try{socket = new Socket ("localhost", 8080);      out = Socket.getoutputstream (); in = Socket.getinputstream ();    Request Server    Out.write ("First request". GetBytes ("UTF-8"));    Out.flush ();                Get server response, Output    byte[] ByteArray = new byte[1024];    int length = In.read (ByteArray);    System.out.println (New String (ByteArray, 0, length, "UTF-8"));        Thread.Sleep (the);        Request Server    Out.write again ("Second request". GetBytes ("UTF-8"));    Out.flush ();        Get the server response again, output    ByteArray = new byte[1024];    Length = In.read (ByteArray);    System.out.println (New String (ByteArray, 0, length, "UTF-8"));        Finally {//close connection in.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


Fork Brother reproduced please indicate the source: http://blog.csdn.net/xiao__gui/article/details/38581355




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.