检查是否收到消息或跳过它(python 3.4)

时间:2015-04-23 11:14:59

标签: python python-3.x

我想问一下如何跳过接收功能。

def client():
    try:
        b = bytes.decode(h.recv(1024))
        print("The recieved message : ",b)
        b1 = str.encode(b)
        c.sendall(b1)
        h.sendall(b1)
        y.sendall(b1)
    except Exception:
        pass
    try:
        g = bytes.decode(y.recv(1024))
        print("The recieved message : ",g)
        g1 = str.encode(g)
        c.sendall(g1)
        h.sendall(g1)
        y.sendall(g1)
    except Exception:
        pass

所以我需要做的是检查是否有来自客户端的消息:

  • 如果是,请打印并发送。
  • 如果不是,请跳过该功能去检查其他客户。

1 个答案:

答案 0 :(得分:0)

您需要轮询机制。最简单的是select

import select

def client():
    sockets, _, _ = select.select([h, y], [], [])
    # If h or y has data, select exits and returns these sockets

    for sock in sockets:
        try:
            data = sock.recv(1024)
            if data == '':
                # sock was disconnected handle that
                continue

            # Process data here
        except Exception:
            continue