Windows 上的 Python select.select() 错误 10022

发布于 2024-11-29 22:55:20 字数 2167 浏览 3 评论 0原文

我得到了一个类(QThread 的子类),它通过 select.select() 在许多套接字上从服务器接收数据:

# -*- coding: utf-8 -*-
from PyQt4.QtCore import QThread, pyqtSignal
import json
import select
class MainSocketThread(QThread) :
    disconnected_by_admin = pyqtSignal()
    disconnected_by_network = pyqtSignal(bool)

    def __init__(self, connects_dict=None) :
        QThread.__init__(self)
        self.connects = connects_dict
        if not self.connects:
            self.connects={}

    def run(self) :
        try:
            while 1 :
                inputready, outputready, exceptready = select.select(self.connects.keys(),
                    [], [])
                for s in inputready :
                    try :
                        data = self.s_[s].recv(4096)
                        if not data :
                            s.close()
                            self.connects.pop(s)
                        else :
                            cmd = json.loads(data)
                            print s, cmd, 'asd'
                            #                        ProcessCommand(s, cmd)
                    except Exception as e:
                        s.close()
                        self.connects.pop(s)
        except Exception as e:
            print e
            self.disconnected_by_network.emit(False)
        self.exec_()

这就是我创建套接字的方式(在其他类中):

self.connections_dict = {}
self.main_socket_thread = MainSocketThread(self.connections_dict)
if not self.s :
    try:
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, port))
    except Exception as e:
        print e, e.__class__()
        self.display_connection_status(False)
    else:
        self.connections_dict[self.s] = self
        self.main_socket_thread.start()
        self.s.send(json.dumps({'command': 'operator_insite',
                                'login': self.settings_dict['login'],
                                'password': hashlib.md5(self.settings_dict['password']).hexdigest()}))
        self.display_connection_status(True)

但是每次尝试从套接字中选择时我都会收到 select.error 10022 。我的代码有什么问题吗?

I got class (subclassed from QThread), that recieve data from server at many sockets by select.select():

# -*- coding: utf-8 -*-
from PyQt4.QtCore import QThread, pyqtSignal
import json
import select
class MainSocketThread(QThread) :
    disconnected_by_admin = pyqtSignal()
    disconnected_by_network = pyqtSignal(bool)

    def __init__(self, connects_dict=None) :
        QThread.__init__(self)
        self.connects = connects_dict
        if not self.connects:
            self.connects={}

    def run(self) :
        try:
            while 1 :
                inputready, outputready, exceptready = select.select(self.connects.keys(),
                    [], [])
                for s in inputready :
                    try :
                        data = self.s_[s].recv(4096)
                        if not data :
                            s.close()
                            self.connects.pop(s)
                        else :
                            cmd = json.loads(data)
                            print s, cmd, 'asd'
                            #                        ProcessCommand(s, cmd)
                    except Exception as e:
                        s.close()
                        self.connects.pop(s)
        except Exception as e:
            print e
            self.disconnected_by_network.emit(False)
        self.exec_()

And that's how i create socket(in other class) :

self.connections_dict = {}
self.main_socket_thread = MainSocketThread(self.connections_dict)
if not self.s :
    try:
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, port))
    except Exception as e:
        print e, e.__class__()
        self.display_connection_status(False)
    else:
        self.connections_dict[self.s] = self
        self.main_socket_thread.start()
        self.s.send(json.dumps({'command': 'operator_insite',
                                'login': self.settings_dict['login'],
                                'password': hashlib.md5(self.settings_dict['password']).hexdigest()}))
        self.display_connection_status(True)

But i got select.error 10022 every time trying to select from sockets. What is wrong with my code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一瞬间的火花 2024-12-06 22:55:20

你确定 self.connects 不为空吗?这让我想起了在 Windows 上将 3 个空列表传递给 select.select() 时遇到的错误。

在任何情况下,10022 都是 EINVAL,意味着提供了无效的参数。因此,我会仔细跟踪传递给引发异常的函数的参数(查看套接字是否打开等......)

are you sure self.connects is not empty ? This reminds me of the error you get on Windows when passing 3 empty lists to select.select().

In any case, 10022 is EINVAL meaning an invalid argument has been supplied. So I'd carefully trace the arguments passed to the function raising the exception (seeing if the sockets are open, etc...)

压抑⊿情绪 2024-12-06 22:55:20

通过临时接收代码解决:

def recv(self, sck):
    data = ''
    sck.settimeout(None)
    data = sck.recv(1024)
    sck.settimeout(0.1)
    while 1:
        line = ''
        try:
            line = sck.recv(16384)
        except socket.timeout:
            break
        if line == '':
            break
        data += line
    return data

Soldev by temporary recieve code:

def recv(self, sck):
    data = ''
    sck.settimeout(None)
    data = sck.recv(1024)
    sck.settimeout(0.1)
    while 1:
        line = ''
        try:
            line = sck.recv(16384)
        except socket.timeout:
            break
        if line == '':
            break
        data += line
    return data
饮湿 2024-12-06 22:55:20

好的。我很久以前就解决了这个问题。这是使用 Pyqt 的解决方案:

class UpQSocket(QTcpSocket):
    data_ready = pyqtSignal(unicode)

def __init__(self):
    QTcpSocket.__init__(self)
    self.wait_len = ''
    self.temp = ''
    self.setSocketOption(QTcpSocket.KeepAliveOption, QVariant(1))
    self.readyRead.connect(self.on_ready_read)

def connectToHost(self, host, port):
    self.temp = ''
    self.wait_len = ''
    self.abort()
    QTcpSocket.connectToHost(self, host, port)

def close(self):
    QTcpSocket.close(self)

def send(self, data):
    self.writeData('%s|%s' % (len(data), data))

def on_ready_read(self):
    if self.bytesAvailable():
        data = str(self.readAll())
        while data:
            if not self.wait_len and '|' in data:#new data and new message
                    self.wait_len , data = data.split('|',1)
                    if match('[0-9]+', self.wait_len) and (len(self.wait_len) <= MAX_WAIT_LEN) and data.startswith('{'):#okay, this is normal length
                        self.wait_len = int(self.wait_len)
                        self.temp = data[:self.wait_len]
                        data = data[self.wait_len:]
                    else:#oh, it was crap
                        self.wait_len , self.temp = '',''
                        return
            elif self.wait_len:#okay, not new message, appending
                tl= int(self.wait_len)-len(self.temp)
                self.temp+=data[:tl]
                data=data[tl:]
            elif not self.wait_len and not '|' in data:#crap
                return
            if self.wait_len and self.wait_len == len(self.temp):#okay, full message
                    self.data_ready.emit(self.temp)
                    self.wait_len , self.temp = '',''
                    if not data:
                        return

Okay. I solved this problem long ago. And here is solution using Pyqt:

class UpQSocket(QTcpSocket):
    data_ready = pyqtSignal(unicode)

def __init__(self):
    QTcpSocket.__init__(self)
    self.wait_len = ''
    self.temp = ''
    self.setSocketOption(QTcpSocket.KeepAliveOption, QVariant(1))
    self.readyRead.connect(self.on_ready_read)

def connectToHost(self, host, port):
    self.temp = ''
    self.wait_len = ''
    self.abort()
    QTcpSocket.connectToHost(self, host, port)

def close(self):
    QTcpSocket.close(self)

def send(self, data):
    self.writeData('%s|%s' % (len(data), data))

def on_ready_read(self):
    if self.bytesAvailable():
        data = str(self.readAll())
        while data:
            if not self.wait_len and '|' in data:#new data and new message
                    self.wait_len , data = data.split('|',1)
                    if match('[0-9]+', self.wait_len) and (len(self.wait_len) <= MAX_WAIT_LEN) and data.startswith('{'):#okay, this is normal length
                        self.wait_len = int(self.wait_len)
                        self.temp = data[:self.wait_len]
                        data = data[self.wait_len:]
                    else:#oh, it was crap
                        self.wait_len , self.temp = '',''
                        return
            elif self.wait_len:#okay, not new message, appending
                tl= int(self.wait_len)-len(self.temp)
                self.temp+=data[:tl]
                data=data[tl:]
            elif not self.wait_len and not '|' in data:#crap
                return
            if self.wait_len and self.wait_len == len(self.temp):#okay, full message
                    self.data_ready.emit(self.temp)
                    self.wait_len , self.temp = '',''
                    if not data:
                        return
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文