使用socket+gevent實現協程併發

One of them發表於2018-08-24

使用協程庫來實現簡單併發

"""
   協程實現併發.

"""
import gevent
from gevent import monkey
import socket

# just like of setBlocking(False)
monkey.patch_socket()  # 讓內建socket封裝為IO多路複用的 socket, 實現了accept不阻塞.

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostbyname(socket.gethostname()), 4444))
server.listen(5)


def work(cnn):
    while True:
        data = cnn.recv(1024)
        if data:
            print(data)
        else:
            cnn.close()
            break


if __name__ == '__main__':
    while True:
        cnn, addr = server.accept()
        print("aasdas")
        gr = gevent.spawn(work, cnn)  # 建立多個協程來服務多client

相關文章