当超时设置为“无”时,在UDP套接字上获得超时。 - Python

时间:2014-02-27 20:04:24

标签: python udp

我在Python 3.3中使用UDP编写连接器

当我将数据发送到UDP端口时,一切正常。问题是,当我没有发送任何数据时,我收到的接收端口每分钟产生一次错误,表示“超时”。在调试时,我使用了socket.gettimeout()函数并返回'None'。

为什么我收到此超时错误?任何帮助将不胜感激!

import socket
from EventArgs import EventArgs
import logging
class UDPServer(object):
"""description of class"""

def __init__(self, onMessageReceivedEvent = '\x00'):
    self.__onMessageReceivedEvent = onMessageReceivedEvent
    self.__s = '\x00'
    self.__r = '\x00'

def openReceivePort(self,port):
    try:
        self.__r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__r.bind(("",port))
        print ("opening port: ", port)

    except socket.error as e:
        logging.getLogger("ConnectorLogger").critical(e)


def openBroadcastPort(self):
    try:
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__s.bind(("",2101))
        print ("opening port: ", 2101)

    except socket.error as e:
        logging.getLogger("ConnectorLogger").critical(e)

def closePorts():
    if self.__r != '\x00':
        self.__r.close()
    if self.__s != '\x00':
        self.__s.close()

def getUDPData(self):
    try:
        data, addr = self.__r.recvfrom(1024)
        if self.__onMessageReceivedEvent != '\x00':
            eventArgs = EventArgs()
            eventArgs.Addr = addr
            eventArgs.Data = data
            self.__onMessageReceivedEvent.fire(self, eventArgs)
    except socket.error as e:
        logging.getLogger("ConnectorLogger").critical(e)

def send(self,ipAddress,port,message):
    try:
        self.__s.sendto(message.encode(),(ipAddress,23456))
    except socket.error as e:
            logging.getLogger("ConnectorLogger").critical(e)

1 个答案:

答案 0 :(得分:0)

我找到了自己问题的答案。我使用socket.setblocking的默认配置为0(非阻塞)。文档说使用此配置相当于使用settimeout值为0.如果我使用阻塞套接字,则相当于使用settimeout值为“None”。一旦我改为阻塞套接字,我就不再看到这个错误了。

socket.setblocking(flag ) - 设置套接字的阻塞或非阻塞模式:如果flag为0,则套接字设置为非阻塞,否则设置为阻塞模式。最初所有套接字都处于阻塞模式。在非阻塞模式下,如果recv()调用未找到任何数据,或者send()调用无法立即处理数据,则会引发错误异常;在阻塞模式下,调用将阻塞,直到它们可以继续。 s.setblocking(0)等同于s.settimeout(0.0); s.setblocking(1)相当于s.settimeout(None)*