Mina、Netty、Twisted一起学(一):实现简单的TCP服务器

释放双眼,带上耳机,听听看~!

MINA、Netty、Twisted为什么放在一起学习?首先,不妨先分别看一下它们官方网站对其的介绍:

MINA:

Apache MINA is a network application framework which helps users develop high performance and high scalability network 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 an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
*

Twisted:

*Twisted is an event-driven networking engine written in Python and licensed under the open source MIT license.
*

(Twisted官网的文案不专业啊,居然不写asynchronous)

从上面简短的介绍中,就可以发现它们的共同特点:event-driven以及asynchronous。它们都是事件驱动、异步的网络编程框架。由此可见,它们之间的共同点还是很明显的。所以我这里将这三个框架放在一起,实现相同的功能,不但可以用少量的精力学三样东西,而且还可以对它们之间进行各方面的对比。

其中MINA和Netty是基于Java语言的,而Twisted是Python语言的。不过语言不是重点,重点的是理念。

使用传统的BIO(Blocking IO/阻塞IO)进行网络编程时,进行网络IO读写时都会阻塞当前线程,如果实现一个TCP服务器,都需要对每个客户端连接开启一个线程,而很多线程可能都在傻傻的阻塞住等待读写数据,系统资源消耗大。

而NIO(Non-Blocking IO/非阻塞IO)或AIO(Asynchronous IO/异步IO)则是通过IO多路复用技术实现,不需要为每个连接创建一个线程,其底层实现是通过操作系统的一些特性如select、poll、epoll、iocp等。这三个网络框架都是基于此实现。

下面分别用这三个框架实现一个最简单的TCP服务器。当接收到客户端发过来的字符串后,向客户端回写一个字符串作为响应。

**Mina:
**


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1public class TcpServer {
2
3   public static void main(String[] args) throws IOException {
4       IoAcceptor acceptor = new NioSocketAcceptor();
5       acceptor.setHandler(new TcpServerHandle());
6       acceptor.bind(new InetSocketAddress(8080));
7   }
8
9}
10
11class TcpServerHandle extends IoHandlerAdapter {
12 
13  @Override
14  public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
15      cause.printStackTrace();
16  }
17
18  // 接收到新的数据
19  @Override
20  public void messageReceived(IoSession session, Object message) throws Exception {
21     
22      // 接收客户端的数据
23      IoBuffer ioBuffer = (IoBuffer) message;
24      byte[] byteArray = new byte[ioBuffer.limit()];
25      ioBuffer.get(byteArray, 0, ioBuffer.limit());
26      System.out.println("messageReceived:" + new String(byteArray, "UTF-8"));
27     
28      // 发送到客户端
29      byte[] responseByteArray = "你好".getBytes("UTF-8");
30      IoBuffer responseIoBuffer = IoBuffer.allocate(responseByteArray.length);
31      responseIoBuffer.put(responseByteArray);
32      responseIoBuffer.flip();
33      session.write(responseIoBuffer);
34  }
35
36  @Override
37  public void sessionCreated(IoSession session) throws Exception {
38      System.out.println("sessionCreated");
39  }
40 
41  @Override
42  public void sessionClosed(IoSession session) throws Exception {
43      System.out.println("sessionClosed");
44  }
45}
46

1
2
1  **Netty:  
2

**


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
1public class TcpServer {
2
3   public static void main(String[] args) throws InterruptedException {
4       EventLoopGroup bossGroup = new NioEventLoopGroup();
5       EventLoopGroup workerGroup = new NioEventLoopGroup();
6       try {
7           ServerBootstrap b = new ServerBootstrap();
8           b.group(bossGroup, workerGroup)
9                   .channel(NioServerSocketChannel.class)
10                  .childHandler(new ChannelInitializer<SocketChannel>() {
11                      @Override
12                      public void initChannel(SocketChannel ch)
13                              throws Exception {
14                          ch.pipeline().addLast(new TcpServerHandler());
15                      }
16                  });
17          ChannelFuture f = b.bind(8080).sync();
18          f.channel().closeFuture().sync();
19      } finally {
20          workerGroup.shutdownGracefully();
21          bossGroup.shutdownGracefully();
22      }
23  }
24
25}
26
27class TcpServerHandler extends ChannelInboundHandlerAdapter {
28
29  // 接收到新的数据
30  @Override
31  public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
32      try {
33          // 接收客户端的数据
34          ByteBuf in = (ByteBuf) msg;
35          System.out.println("channelRead:" + in.toString(CharsetUtil.UTF_8));
36         
37          // 发送到客户端
38          byte[] responseByteArray = "你好".getBytes("UTF-8");
39          ByteBuf out = ctx.alloc().buffer(responseByteArray.length);
40          out.writeBytes(responseByteArray);
41          ctx.writeAndFlush(out);
42         
43      } finally {
44          ReferenceCountUtil.release(msg);
45      }
46  }
47 
48  @Override
49  public void channelActive(ChannelHandlerContext ctx) {
50      System.out.println("channelActive");
51  }
52 
53  @Override
54  public void channelInactive(ChannelHandlerContext ctx){
55      System.out.println("channelInactive");
56  }
57
58  @Override
59  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
60      cause.printStackTrace();
61      ctx.close();
62  }
63}
64

1
2
1  **Twisted:  
2

**


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1# -*- coding:utf-8 –*-
2
3from twisted.internet.protocol import Protocol
4from twisted.internet.protocol import Factory
5from twisted.internet import reactor
6
7class TcpServerHandle(Protocol):
8    
9    # 新的连接建立
10    def connectionMade(self):
11        print 'connectionMade'
12        
13    # 连接断开
14    def connectionLost(self, reason):
15        print 'connectionLost'
16    
17    # 接收到新数据
18    def dataReceived(self, data):
19        print 'dataReceived', data
20        self.transport.write('你好')
21
22factory = Factory()
23factory.protocol = TcpServerHandle
24reactor.listenTCP(8080, factory)
25reactor.run()
26

1
2
1 上面的代码可以看出,这三个框架实现的TCP服务器,在连接建立、接收到客户端传来的数据、连接关闭时,都会触发某个事件。例如接收到客户端传来的数据时,MINA会触发事件调用messageReceived,Netty会调用channelRead,Twisted会调用dataReceived。编写代码时,只需要继承一个类并重写响应的方法即可。这就是event-driven事件驱动。
2

下面是Java写的一个TCP客户端用作测试,客户端没有使用这三个框架,也没有使用NIO,只是一个普通的BIO的TCP客户端。

TCP在建立连接到关闭连接的过程中,可以多次进行发送和接收数据。下面的客户端发送了两个字符串到服务器并两次获取服务器回应的数据,之间通过Thread.sleep(5000)间隔5秒。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
1public class TcpClient {
2  
3   public static void main(String[] args) throws IOException, InterruptedException {
4      
5      
6       Socket socket = null;
7       OutputStream out = null;
8       InputStream in = null;
9      
10      try{
11         
12          socket = new Socket("localhost", 8080);      
13          out = socket.getOutputStream();
14          in = socket.getInputStream();
15         
16          // 请求服务器
17          out.write("第一次请求".getBytes("UTF-8"));
18          out.flush();
19                 
20          // 获取服务器响应,输出
21          byte[] byteArray = new byte[1024];
22          int length = in.read(byteArray);
23          System.out.println(new String(byteArray, 0, length, "UTF-8"));
24         
25          Thread.sleep(5000);
26         
27          // 再次请求服务器
28          out.write("第二次请求".getBytes("UTF-8"));
29          out.flush();
30         
31          // 再次获取服务器响应,输出
32          byteArray = new byte[1024];
33          length = in.read(byteArray);
34          System.out.println(new String(byteArray, 0, length, "UTF-8"));
35         
36         
37      } finally {
38          // 关闭连接
39          in.close();
40          out.close();
41          socket.close();
42      }
43     
44  }
45
46}
47

1
2
1 用客户端分别测试上面三个TCP服务器:  
2

MINA服务器输出结果:

sessionCreated
messageReceived:第一次请求
messageReceived:第二次请求
sessionClosed

Netty服务器输出结果:

channelActive
channelRead:第一次请求
channelRead:第二次请求
channelInactive

Twisted服务器输出结果:

connectionMade
dataReceived: 第一次请求
dataReceived: 第二次请求
connectionLost

作者:叉叉哥   转载请注明出处:http://www.voidcn.com/article/p-sbbsotpa-mb.html

给TA打赏
共{{data.count}}人
人已打赏
安全技术

网站制作需要素材的实用网站

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索