Java Network Programming Reference article

Source: Internet
Author: User
Tags throwable

Transferred from:

MINA, Netty, twisted Why do you study together? First, take a look at their official website to introduce them:


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 is a asynchronous Event-driven Network application framework for rapid development of maintainable high PE Rformance protocol servers & clients.


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, with the underlying implementation of some features of the operating system such as SELECT, poll , Epoll, IOCP and so on. 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.


public class TCPServer {public static void main (string[] args) throws IOException {Ioacceptor acceptor =          New Niosocketacceptor ();          Acceptor.sethandler (New Tcpserverhandle ());      Acceptor.bind (new inetsocketaddress (8080));  }} class Tcpserverhandle extends Iohandleradapter {@Override public void exceptioncaught (iosession      Session, Throwable Cause) throws Exception {cause.printstacktrace ();                    }//received new data @Override public void Messagereceived (iosession session, Object message) throws Exception {          Receive client data Iobuffer Iobuffer = (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); } @Override public void sessioncreated (Iosession session) throws Exception {System.out.println ("Sess      Ioncreated "); } @Override public void sessionclosed (Iosession session) throws Exception {System.out.println ("s      Essionclosed ");   }  }


public class TCPServer {public static void main (string[] args) throws Interruptedexception {Eventloopgro          Up Bossgroup = new Nioeventloopgroup ();          Eventloopgroup Workergroup = new Nioeventloopgroup ();              try {serverbootstrap b = new Serverbootstrap (); (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Childhan Dler (New channelinitializer<socketchannel> () {@Override public vo ID initchannel (Socketchannel ch) throws Exception {Ch.pipel                          INE (). AddLast (New Tcpserverhandler ());              }                      });              Channelfuture f = b.bind (8080). sync (); (). Closefuture (). sync ();              } finally {workergroup.shutdowngracefully ();          Bossgroup.shutdowngracefully (); }      }    }    Class Tcpserverhandler extends Channelinboundhandleradapter {//Receive new data @Override public void Channe               Lread (Channelhandlercontext ctx, Object msg) throws Unsupportedencodingexception {try {//Receive client's 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); }} @Override public void channelactive (Channelhandlercontext ctx) {System.out.println ("Cha      Nnelactive "); } @Override public void channelinactive (Channelhandlercontext ctx) {System.out.println ("Channelin      Active ");    }    @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {Cause.printstacktrac          E ();      Ctx.close ();   }  }


#-*-coding:utf-8–*-from    twisted.internet.protocol Import protocol from  Twisted.internet.protocol import Factory  from twisted.internet import reactor    class Tcpserverhandle (Protocol):            # New Connection Build      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 = Tcpserverhandle  reactor.listentcp (8080, factory)  

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 = NULL;          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 = (ByteArray);                            System.out.println (New String (ByteArray, 0, length, "UTF-8"));                            Thread.Sleep (5000);              Request Server Out.write again ("Second request". GetBytes ("UTF-8"));                            Out.flush ();   Get the server response again, output ByteArray = new byte[1024];           Length = (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:

Messagereceived: First time request
Messagereceived: Second Request

Netty Server Output results:

Channelread: First time request
Channelread: Second Request

Twisted Server Output results:

DataReceived: First time request
DataReceived: Second Request

Java Network Programming Reference article

Related Article

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: 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.