单线程下实现并发的套接字通信

客户端:

from threading import Thread,current_thread
from socket import *

def client():
client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))

n=0
while True:
msg='%s say hello %s' %(current_thread().name,n)
n+=1
client.send(msg.encode('utf-8'))
data=client.recv(1024)
print(data.decode('utf-8'))

if __name__ == '__main__':
for i in range(500):
t=Thread(target=client)
t.start()

服务端:
from gevent import monkey;monkey.patch_all()
from socket import *
from gevent import spawn

def comunicate(conn):
while True: # 通信循环
try:
data = conn.recv(1024)
if len(data) == 0: break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()


def server(ip, port, backlog=5):
server = socket(AF_INET, SOCK_STREAM)
server.bind((ip, port))
server.listen(backlog)

while True: # 链接循环
conn, client_addr = server.accept()
print(client_addr)

# 通信
spawn(comunicate,conn)

if __name__ == '__main__':
g1=spawn(server,'127.0.0.1',8080)
g1.join()
 
posted @ 2018-09-22 17:38  不沉之月  阅读(203)  评论(0编辑  收藏  举报