一:基于多线程实现套接字
可添加多个客户端
from socket import * from threading import Thread 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) # 通信 t = Thread(target=comunicate, args=(conn,)) t.start() if __name__ == '__main__': s = Thread(target=server, args=('127.0.0.1', 8081)) s.start()
from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8081)) while True: msg = input('>>:').strip() if len(msg) == 0: continue client.send(msg.encode('utf-8')) data = client.recv(1024) print(data.decode('utf-8'))
from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8081)) while True: msg = input('>>:').strip() if len(msg) == 0: continue client.send(msg.encode('utf-8')) data = client.recv(1024) print(data.decode('utf-8'))
二:gevent
通过gevent实现单线程下的socket并发(from gevent import monkey;patch_all () 一定要放到导入socket模块之前,否则gevent无法识别socket的阻塞)
from gevent import monkey;monkey.patch_all() from gevent import spawn,joinall #pip3 install gevent import time def play(name): print('%s play 1'%name) time.sleep(5) print('%s play 2'%name) def eat(name): print('%s eat 1' % name) time.sleep(3) print('%s eat 2' % name) start=time.time() g1=spawn(play,'dsd') g2=spawn(eat,'dsd') joinall([g1,g2]) print('主',time.time()-start)
三:单线程下实现并发的套接字通信
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(10): t=Thread(target=client()) t.start()
from gevent import mokey; mokey.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.uppper()) 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()