041.基于协程的高并发实现

041.基于单线程、协程的高并发实现

文章目录

  • 一、基于单线程的套接字并发
    • (一)服务端
    • (二)客户端
  • 二、基于协程的套接字并发
    • (一)服务端
    • (二)客户端

一、基于单线程的套接字并发

(一)服务端

from socket import socket
from threading import Thread

server = socket()

server.bind(('127.0.0.1', 8080))
server.listen(5)

def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0: break
            print(data)
            conn.send(data.upper())
        except Exception as e:
            print(e)
            break
    conn.close()

while True:
    conn, addr = server.accept()
    t = Thread(target=talk, args=(conn,))
    t.start()

(二)客户端

from socket import socket
from threading import Thread, current_thread

def task():
    cli = socket()
    cli.connect(('127.0.0.1',8080))
    while True:
        ss = '%s say hello' % current_thread().name
        cli.send(ss.encode('utf-8'))
        data = cli.recv(1024)
        print(data)

for i in range(5):
    t = Thread(target=task)
    t.start()

二、基于协程的套接字并发

(一)服务端

from gevent import monkey, spawn; monkey.patch_all()

from socket import socket

def make_server(ip, port):
    server = socket()
    server.bind((ip, port))
    server.listen(5)

    while True:
        conn, addr = server.accept()
        spawn(task, conn)   # 这里还需要join吗?不能加,我们不希望它夯在这

def task(conn):
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0: break
            print(data)
            conn.send(data.upper())
        except Exception as e:
            print(e)
            break
    conn.close()

if __name__ == '__main__':
    g = spawn(make_server, '127.0.0.1', 8080)
    g.join()

(二)客户端

from socket import socket
from threading import Thread, current_thread

def task():
    cli = socket()
    cli.connect(('127.0.0.1',8080))
    while True:
        ss = '%s say hello' % current_thread().name
        cli.send(ss.encode('utf-8'))
        data = cli.recv(1024)
        print(data)

for i in range(5):
    t = Thread(target=task)
    t.start()

你可能感兴趣的:(python基础学习)