併發編程實戰之併發下的socket套接字編程

1、python單線程下實現多個socket併發

1.1 服務端

import sys
# import socket
import time
import gevent
from gevent import socket
from gevent import monkey

monkey.patch_all()


# 相似於python中的黑魔法,把不少模塊的阻塞的變成非阻塞的,好比socket中的rece和send都變
# 爲不阻塞了


def server(port):
    s = socket.socket()
    s.bind(("127.0.0.1", port))
    s.listen(2000)
    while True:
        cli, add = s.accept()
        gevent.spawn(handle_request, cli)
        # 經過gevent的啓動一個協程,把客戶端的socket對象傳進去


def handle_request(s):
    try:
        while True:
            data = s.recv(1024)
            print("收到的信息:", str(data, encoding="utf-8"))
            s.send(data)
            if not data:
                s.shutdown(socket.SHUT_WR)
                # 把和客戶端這個連接銷燬
    except Exception as ex:
        print(ex)
    finally:
        s.close()


if __name__ == '__main__':
    server(8000)

1.2 客戶端

import socket
import gevent
import threading
import multiprocessing
'''
ip_bind = ("127.0.0.1",8000)
c = socket.socket()
c.connect(ip_bind)
while True:
    data = input("客戶端:")
    c.send(bytes(data,encoding="utf-8"))
    data = c.recv(1024)
    print("服務端:",str(data,encoding="utf-8"))
 
c.close()
'''
import socket
import gevent
ip_bind = ("127.0.0.1",8000)
c = socket.socket()
c.connect(ip_bind)
def f(n):
    while True:
        # c.send(bytes(n,encoding="utf-8"))
        data = str(n)
        c.send(bytes(data,encoding="utf-8"))
        data = c.recv(1024)
        print("server:",str(data,encoding="utf-8"))
    c.close()
x = []
if __name__ == '__main__':
    l = []
    """
    多線程實現併發客戶端
        for i in range(500):
         t = threading.Thread(target=f,args=[str(i),])
         t.start()
         l.append(t)
    for t in l:
         t.join()
 
    """
    # 多進程實現併發客戶端
    for i in range(100):
        p = multiprocessing.Process(target=f,args=[i,])
        p.start()
        l.append(p)
    for p in l:
        p.join()
相關文章
相關標籤/搜索