Code example of coroutine implementing TCP connection in python

不言
Release: 2018-10-13 16:49:44
forward
2239 people have browsed it

The content of this article is about the code examples of coroutines in python to implement TCP connections. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In network communication, each connection must create a new thread (or process) for processing. Otherwise, a single thread cannot accept connections from other clients while processing the connection. So we try to use coroutines to implement the server's response to multiple clients.
The same architecture as the single TCP communication, except that coroutines are used to implement multiple tasks at the same time.

#服务端
import socket
from gevent import monkey
import gevent
monkey.patch_all()
def handle_conn(seObj):
    while True:
        re_Data  = seObj.recv(1024).decode('utf-8')
        if re_Data == 'quit':
            break
        print('client>>',re_Data)
        value  = input("server>>")
        se_Data = seObj.send(value.encode('utf-8'))
        if se_Data == 'quit':
            break
if __name__ == '__main__':
    server = socket.socket()
    server.bind(('192.168.1.227',9876))
    print("服务已开启")
    server.listen(4)
    while True:
        seObj,add = server.accept()
        gevent.spawn(handle_conn,seObj)
    seObj.close()
    server.close()
Copy after login
rrree

The above is the detailed content of Code example of coroutine implementing TCP connection in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template