Python并发编程-IO模型-非阻塞IO实现SocketServer

2021-06-18 05:03

阅读:364

标签:for   hello   int   accept   lis   end   ...   实现   sock   

  • Server.py
import socket

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.setblocking(False) #把socket中所有需要阻塞的方法都设为非阻塞IO, recv,accept, recvfrom
sk.listen()
conn_l = [] #保存所有来请求server端conn连接
del_conn = [] #用来存储所有已经与server端断开的conn
while True:
    try:
        conn,addr = sk.accept() #不阻塞,但没人连我会报错,用try...except,直到连接建立
        print('连接建立了',addr)
        conn_l.append(conn) 
    except BlockingIOError:
        for con in conn_l:
            try:
                msg = con.recv(1024)  #不阻塞,但是没有消息会报错
                if msg == b'': #如果msg为空, 把相应的连接加入del_conn,然后继续
                    del_conn.append(con)
                    continue
                print(msg)
                con.send(b'hi')
            except BlockingIOError: pass
        for con in del_conn:
            conn.close()
            conn_l.remove(con) #上次相应del_conn项
        del_conn.clear() #清除del_conn列表
 
  • Client.py
import socket
import time
import threading
def func():
    sk = socket.socket()
    sk.connect(('127.0.0.1',8080))
    sk.send(b'hello')
    time.sleep(0.1)
    sk.send(b'world')
    time.sleep(0.1)
    print(sk.recv(1024))
    sk.close()

for i in range(20):
    threading.Thread(target=func).start()

技术分享图片

Python并发编程-IO模型-非阻塞IO实现SocketServer

标签:for   hello   int   accept   lis   end   ...   实现   sock   

原文地址:https://www.cnblogs.com/konglinqingfeng/p/9718122.html


评论


亲,登录后才可以留言!