Mina, Netty, and Twisted (1): implement a simple TCP server, nettytwisted

Source: Internet
Author: User

Mina, Netty, and Twisted (1): implement a simple TCP server, nettytwisted

Why are MINA, Netty, and Twisted learning together? First, let's take a look at their official website's introduction:

MINA:

Apache MINA isNetwork application frameworkWhich helps users develop high performance and high scalability network applications easily. It provides an abstractEvent-driven asynchronousAPI over various transports such as TCP/IP and UDP/IP via Java NIO.

Netty:

Netty isAsynchronous event-driven network application frameworkFor rapid development of maintainable high performance protocol servers & clients.

Twisted:

Twisted isEvent-driven networking engineWritten in Python and licensed under the open source MIT license.

(The text on the Twisted official website is not professional, so asynchronous is not written)

From the brief introduction above, we can find their common features: event-driven and asynchronous. They are bothEvent-driven and Asynchronous Network Programming Framework. It can be seen that the commonalities between them are quite obvious. So here I put these three frameworks together to implement the same functions, not only can I learn three things with a small amount of energy, but also can compare them in various aspects.

MINA and Netty are based on Java, while Twisted is based on Python. However, language is not the focus, but philosophy.

When network programming using traditional BIO (Blocking IO/Blocking IO), the current thread will be blocked during network IO read/write. If a TCP server is implemented, you need to enable a thread for each client connection, and many threads may block waiting for reading and writing data, causing high system resource consumption.

NIO (Non-Blocking IO/Non-Blocking IO) or AIO (Asynchronous IO/Asynchronous IO) is implemented through IO multiplexing technology, and there is no need to create a thread for each connection, its underlying implementation is based on some features of the operating system, such as select, pool, epoll, and iocp, which are not the focus of this article. These three network frameworks are based on this implementation.

The following uses the three frameworks to implement a simple TCP server. After receiving the string sent from the client, write back a string to the client as a response.

Mina:

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 ();} // receives new data @ Override public void messageReceived (IoSession session, Object message) throws Exception {// receives 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 ("sessionCreated") ;}@ Override public 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> () {@ Override public void initChannel (SocketChannel ch) throws Exception {ch. pipeline (). addLast (new TcpServerHandler () ;}}); ChannelFuture f = B. bind (8080 ). sync (); f. channel (). closeFuture (). sync ();} finally {workerGroup. shutdownGracefully (); bossGroup. shutdownGracefully () ;}} class TcpServerHandler extends ChannelInboundHandlerAdapter {// receives new data @ Override public void channelRead (ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {try {// receives client data ByteBuf in = (ByteBuf) msg; System. out. println ("channelRead:" + in. toString (CharsetUtil. UTF_8); // sent to the 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 ("channelActive") ;}@ Override public void channelInactive (ChannelHandlerContext ctx) {System. out. println ("channelInactive") ;}@ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {cause. printStackTrace (); ctx. close ();}}

Twisted:

#-*-Coding: UTF-8-*-from twisted. internet. protocol import Protocol from twisted. internet. protocol import Factory from twisted. internet import reactor class TcpServerHandle (Protocol): # create a new connection def connectionMade (self): print 'ononmade '# Disconnect def connectionLost (self, reason ): print 'ononlost' # receives the new data def dataReceived (self, data): print 'datance', data self. transport. write (' ') factory = Factory () factory. protocol = TcpServerHandle reactor. listenTCP (8080, factory) reactor. run ()

The above Code shows that the TCP servers implemented by the three frameworks will trigger an event when the connection is established, the data sent from the client is received, and the connection is closed. For example, when receiving data from the client, MINA will trigger the event to call messageReceived, Netty will call channelRead, and Twisted will call dataReceived. When writing code, you only need to inherit a class and override the response method. This is the event-driven event driver.

The following is a TCP client written in Java for testing. The client does not use these three frameworks, nor does it use NIO. It is just a common bio tcp client.

TCP can send and receive data multiple times when establishing a connection to close the connection. The following client sends two strings to the server and obtains the server response data twice. The interval between them is 5 seconds through Thread. sleep (5000.

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 the server response and output byte [] byteArray = new byte [1024]; int length = in. read (byteArray); System. out. println (new String (byteArray, 0, length, "UTF-8"); Thread. sleep (5000); // request the server out again. write ("second request ". getBytes ("UTF-8"); out. flush (); // obtain the server response again and output byteArray = new byte [1024]; length = in. read (byteArray); System. out. println (new String (byteArray, 0, length, "UTF-8");} finally {// close the connection in. close (); out. close (); socket. close ();}}}

Use the client to test the preceding three TCP servers:

MINA server output result:

SessionCreated
MessageReceived: the first request
MessageReceived: second request
SessionClosed

Netty server output result:

ChannelActive
ChannelRead: the first request
ChannelRead: second request
ChannelInactive

Twisted server output result:

ConnectionMade
DataReceived: the first request
DataReceived: second request
ConnectionLost


What is the difference between interfaces provided by netty webservice servlets?

Netty provides asynchronous, event-driven network application frameworks and tools to quickly develop high-performance, high-reliability network servers and client programs. That is to say, Netty is a NIO-based client and server-side programming framework. Using Netty ensures that you can quickly and easily develop a network application, such as a customer who implements a certain protocol, server applications. Netty simplifies and streamlined the programming and development process of network applications, such as TCP and UDP socket service development.
Netty is a NIO-based server (simplified socket development of TCP/UDP ).
Java writes that Web Services are online application Services released by enterprises to meet their specific business needs. Other companies or application software can access and use this online service over the Internet. In fact, the main goal of WebService is cross-platform interoperability. To achieve this goal, WebService is fully based on XML (Extensible Markup Language), XSD (XMLSchema), and other standards independent of the platform and software vendors, is a new platform for creating interoperable and distributed applications. From this we can see that in the following three cases, using WebService will bring great benefits.
Third-party services (such as http and tcp) are provided ).
Servlet: A small application executed by the server. It is a server component. For example, HttpServlet is used to process Http requests, accept requests, and dynamically generate responses.
The three have different concerns:
Netty provides a NIO-Based Server framework (simplified socket development of TCP/UDP), similar to mina. For example, implement a web server.
Web services focus on web services and establish a set of rules to enable cross-platform/cross-application Coco access. Such as the weather forecast interface and google Map interface.

How can netty and tomcat be used together?

There is no direct relationship between the two. netty should be a network framework similar to mina, while tomcat is a servlet container.
 

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