Home > Article > Backend Development > Code example of coroutine implementing TCP connection in python
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()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!