Python BlockingIOError:[Errno 11]发送数据时资源暂时不可用

时间:2019-04-30 19:38:29

标签: python sockets

我正在尝试通过客户端套接字发送字典,但是迟早会出现此错误。我不知道如何解决这个问题,有什么建议吗?

我的操作系统:Linux Mint 19.1 Python:3.6.7

我已经尝试过:https://stackoverflow.com/a/38526115/11434238,但没有结果

服务器:

def accept_connection(conn, sel):
    client, addr = conn.accept()
    client.setblocking(0)
    print(f'New connection from {addr[0]}:{addr[1]}.')
    sel.register(client, client_events, client_data)

def handle_connection(key, mask, sel):
    client = key.fileobj
    # data = key.data
    if mask & selectors.EVENT_READ:
        header = int(client.recv(5).decode('utf-8').strip())

        if header == 0:
            # client leaved server or connection broken
            print('Closing connection')
            sel.unregister(client)
            client.close()
        else:    
            received = client.recv(header)
            print(header, received, sep="\n")


server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind((HOST ,PORT))
server.listen(SLOTS)

selector.register(server, selectors.EVENT_READ, data = None)

while True:
    events = selector.select()
    for key, mask in events:
        sock = key.fileobj
        if key.data is None:
            accept_connection(sock, selector)
        else:
           handle_connection(key, mask, selector)

客户端:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
sock.connect_ex((HOST, PORT))
info = {
    "id": 1,
    "x": 10,
    "y": 10
}

def send_data(socket = sock):
    data = bytes(json.dumps(info), 'utf-8')
    header = bytes(f'{len(data):<5}', 'utf-8')
    print(header)
    socket.send(header)
    socket.send(data)


while True:
    send_data()

0 个答案:

没有答案