简体   繁体   English

多个客户端使用eventlet,需要非阻塞IO代码

[英]Multiple client using eventlet, need non-blocking IO code

Below is the code of eventlet server. 下面是eventlet服务器的代码。 I want to do Non-blocking IO. 我想做非阻塞IO。 To test the non-blocking IO, i used below code as server. 为了测试非阻塞IO,我使用下面的代码作为服务器。

import eventlet
from eventlet.green import socket


def fib(n):
    if n == 1 or n == 2:
        return 1

    return (fib(n-1) + fib(n-2))

def handle_socket(reader, writer):
    print ("client connected")
    while True:
        line = reader.readline()
        if not line:
            break
        writer.write(line)
        writer.flush()
        n = line.rstrip()
        print ("echoed", int(n))
        print(fib(int(n)))
    print ("disconnected")

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 6000))
server.listen(100)
print ("server listening on port 6000")
print('called me...')

while True:
    sock, addr = server.accept()

    eventlet.spawn(handle_socket, sock.makefile('r'), sock.makefile('w'))

To test at the client side,(on windows), did below steps, 要在客户端进行测试,(在Windows上),执行以下步骤,

telnet localhost 6000
35

To get the 35th Fibonacci series number, on my laptop it takes around 15secs . 要获得第35个Fibonacci系列号码,在我的笔记本电脑上需要大约15秒 Meanwhile, i open another terminal and give input of smaller fibonacci number like 5 or 6(which takes like 2/3 secs) . 与此同时,我打开另一个终端并输入较小的斐波纳契数,如5或6(需要2/3秒) But this server code is running sequentially, after the output of the 35th number is calculated then only the other smaller number output is printed. 但是,在计算出第35个数字的输出之后,此服务器代码按顺序运行,然后仅打印另一个较小的数字输出。 Is there is way to make the same code "concurrent" or "parallelism". 是否有办法使相同的代码“并发”或“并行”。

Your best option is to run blocking code in separate OS thread. 您最好的选择是在单独的OS线程中运行阻塞代码。 Eventlet has built in thread pool in eventlet.tpool [1]. Eventlet在eventlet.tpool [1]中内置了线程池。 Simpler API for single function call: 单个函数调用的简单API:

result = eventlet.tpool.execute(fib, int(n))

[1] http://eventlet.net/doc/threading.html#tpool-simple-thread-pool [1] http://eventlet.net/doc/threading.html#tpool-simple-thread-pool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM