python3 单线程(gevent)实现并发的socket通讯
Posted lilyxiaoyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 单线程(gevent)实现并发的socket通讯相关的知识,希望对你有一定的参考价值。
# -*- coding: utf-8 -*-
from gevent import monkey; monkey.patch_all()import gevent
from socket import *
def talk(conn):
while 1: # 循环通讯
try:
from_client_msg = conn.recv(1024)
if not from_client_msg:break
print("来自客户端的消息:%s" %(from_client_msg))
conn.send(from_client_msg.upper())
except:
break
conn.close()
if __name__ == ‘__main__‘:
server = socket()
ip_port = ("127.0.0.1", 8001)
server.bind(ip_port)
server.listen(5)
while 1: # 循环连接
conn, addr = server.accept()
gevent.spawn(talk, conn) # 开启一个协程
server.close()
# -*- coding: utf-8 -*-
from socket import *
client = socket()
ip_port = ("127.0.0.1", 8001)
client.connect(ip_port)
while 1: # 循环通讯
inp = input(">>:").strip()
if not inp: continue
if inp.upper() == "Q": break
client.send(inp.encode())
from_server_msg = client.recv(1024)
print("来自服务端的消息:", from_server_msg)
client.close()
以上是关于python3 单线程(gevent)实现并发的socket通讯的主要内容,如果未能解决你的问题,请参考以下文章
并发编程 - 协程 - 1.协程概念/2.greenlet模块/3.gevent模块/4.gevent实现并发的套接字通信