sock.setblocking(0)
ready = select.select([sock], [], [], timeout)
try:
if ready[0]:
status = sock.recv(1024)
return status
else:
print "Time out Occured, Disconnecting..."
我有socket receive函数,每当客户端的某些状态发生变化时,它都会接收。同时,我会处理其他活动。
由于在其他一些活动之间收到sock receive,我错过了该receive,无法处理该receive。
所以我怎么能随时收到最新的消息!
请注意我是一个蟒蛇新手。
最佳答案
如果需要后台IO,生成一个新线程来处理IO可能是最简单的方法:
import socket
import threading
import queue
class ClientReceiver(threading.Thread):
RECV_BUF_SIZE = 1024
QUEUE_SIZE = 2
def __init__(self, sock, recv_buf_size=None, queue_size=None, *args, **kwargs):
super(ClientReceiver, self).__init__(*args, **kwargs)
# set thread as daemon thread, we don't want to
# wait for this thread on interpreter exit.
self.setDaemon(True)
self.sock = sock
self.recv_buf_size = recv_buf_size or self.RECV_BUF_SIZE
self.queue_size = queue_size or self.QUEUE_SIZE
def run(self):
sock = self.sock
try:
while True:
data = sock.recv(self.recv_buf_size)
self.queue.put(data)
except Exception as ex:
# handle errors
raise
# Usage example:
sock = ...
receiver = ClientReceiver(sock)
receiver.start()
data = receiver.queue.get(block=False)
线程在数据可用时立即从网络中检索数据并将其放入队列。线程阻塞如果队列已满,则可能需要或不需要其他策略。
使用
receiver.queue
随时从队列中检索数据。这缺少正确关闭客户机套接字的代码,但您可能了解了基本思想。