仅在可用时才接收数据,在python套接字中

时间:2017-08-28 21:03:03

标签: python sockets tcp

我希望只有在有空的情况下才会收到数据。比如Arduino中的if there is data: receive and print else: print 'No data' 。我想要一个像这样的代码:

a={ {'a', 'b', 'c','d'},{''}, {'e', 'f', 'g', 'h'},{''} }

事实上,我不希望程序只是为了接收数据而停止。

1 个答案:

答案 0 :(得分:3)

select.select可用于轮询套接字是否有数据。这是一个简单的例子:

import socket
import select
s = socket.socket()
s.bind(('',8000))
s.listen(1)
readable = [s] # list of readable sockets.  s is readable if a client is waiting.
i = 0
while True:
    # r will be a list of sockets with readable data
    r,w,e = select.select(readable,[],[],0)
    for rs in r: # iterate through readable sockets
        if rs is s: # is it the server
            c,a = s.accept()
            print('\r{}:'.format(a),'connected')
            readable.append(c) # add the client
        else:
            # read from a client
            data = rs.recv(1024)
            if not data:
                print('\r{}:'.format(rs.getpeername()),'disconnected')
                readable.remove(rs)
                rs.close()
            else:
                print('\r{}:'.format(rs.getpeername()),data)
    # a simple spinner to show activity
    i += 1
    print('/-\|'[i%4]+'\r',end='',flush=True)

两个客户端连接,发送内容并断开连接的示例:

('127.0.0.1', 2983): connected
('127.0.0.1', 2983): b'hello'
('127.0.0.1', 2985): connected
('127.0.0.1', 2985): b'there'
('127.0.0.1', 2983): disconnected
('127.0.0.1', 2985): disconnected
<spinner activity here>

您也可以在套接字上调用.setblocking(0),但是当您在套接字上.accept().recv()并且没有连接就绪或没有数据要接收时,您必须处理异常,例如:

try:
    data = s.recv(1024)
    print(data)
except BlockingIOError:
    print('no data')