Python 2.7 socket.accept()方法是返回阻塞套接字还是非阻塞套接字? [英] Does a Python 2.7 socket.accept() method return a blocking socket or a non blocking socket?

查看:185
本文介绍了Python 2.7 socket.accept()方法是返回阻塞套接字还是非阻塞套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2.7中使用套接字模块:



1.我从socket.accept()方法收到一个套接字对象。

2.我检查了套接字对象的超时,它返回-1.0。我认为这意味着套接字对象处于阻塞模式。

3.然而,当我在套接字对象上调用recv方法时,我收到错误:

[Errno 10035]无法立即完成非阻塞套接字操作

4.如果套接字对象是非阻塞的,则此错误才有意义。套接字对象应该阻塞,直到数据到达。



为什么套接字对象在阻塞时没有阻塞?



注意:我在socket上设置了一个超时,调用了accept()方法。这可能导致返回的套接字对象也是非阻塞的吗?如果是这样,我很想听听有关为什么会发生这种情况的解释。



Using the socket module in python 2.7:

1. I received a socket object from a socket.accept() method.
2. I checked the timeout of the socket object and it returned -1.0. I think this means the socket object is in blocking mode.
3. However when I call the recv method on the socket object I receive the error:
[Errno 10035] A non-blocking socket operation could not be completed immediately
4. This error only makes sense if the socket object is non blocking. The socket object should block until data arrives.

Why is the socket object non blocking when it should be blocking?

NOTE: I have set a timeout on the socket which called the accept() method. Could this be causing the returned socket object to be non blocking as well? If so, I would grateful to hear an explanation as to why this is happening.

def wait_for_connection(self):
    connection, client_address = self.sock.accept()
    print 'connected to ' + str(client_address)
    self.connections.append(connection)







def read_from_connections(self):
    for connection in self.connections:
        try:
            command = connection.recv(1024)
            if command:
                print command
        except socket.error, error:
            print error  # error 10035.
            print connection._sock.timeout  # returns -1
            if error.errno != errno.EWOULDBLOCK:
                raise







我尝试过:



我尝试使用内置的dir()方法在套接字对象内的某处查找blocking_mode属性,但我没有成功。所以我使用timeout属性作为套接字是阻塞还是非阻塞的指示符。如果这个假设是错误的,请告诉我。




What I have tried:

I've tried looking for blocking_mode property somewhere inside the socket object using the built in dir() method, but I was not successful. So I used the timeout property as an indicator of whether the socket is blocking or non blocking. Please let me know if this assumption is wrong.

推荐答案

不要猜测,最好转到套接字编程HOWTO - Python 2.7.13文档 [ ^ ]清楚解释。
Rather than guessing, it is better to go to the documentation at Socket Programming HOWTO — Python 2.7.13 documentation[^] where it is clearly explained.


这篇关于Python 2.7 socket.accept()方法是返回阻塞套接字还是非阻塞套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆