开发者

Python socket strangly hanged - sometimes (client connects with flash) - python 3.2

I experience strange behavior of sockets in Python (3.2). Client connects to my application using Flash. Most of the time there is nothing unusual but sometimes python crashes in a way that should not have taken place - enter into infinite loops. Below I attach to the loop code and error message in the log. Python hang on bytesRecived = sock.recv(64) and receive b'' witch is visible in log.

code:

try:
    buff = ''
    allBytesRecived = []
    timeout = sock.gettimeout()
    sock.settimeout(10.0)
    tries = 0
    while len(buff) < 64 and tries < 64:
        tries += 1
        bytesRecived = sock.recv(64)
        allBytesRecived.append(bytesRecived)
        comm = str(bytesRecived, config.encoding)
        buff += comm

        #flash connection and his strage security policy
        if buff[:24] == config.flash.policy_request:
            cross = open(config.flash.crossdomain,'rb').read()
            cross+=b'\x00' #end string
            sock.send(cross);
            r开发者_Python百科aise FlashCrossdomainException()

    if len(buff) < 64:
        logger.critical('Hanged! buff=%s bytes=%s timeout=%s' % (repr(buff), repr(allBytesRecived), repr(sock.gettimeout())))
        raise InvalidSessionException('Unknown error')
    sock.settimeout(timeout)

except FlashCrossdomainException as e:
    raise e
except socket.timeout:
    raise InvalidSessionException('Timeout on signing in to system')
except socket.error as e:
    logger.exception(e)
    raise InvalidSessionException('Unknown IO error')
except Exception as e:
    logger.exception(e)
    raise InvalidSessionException('Unknown error')

log error:

CRITICAL: Hanged! buff='' bytes=[b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'', b''] timeout=10.0


python's socket module closely matches the BSD socket API.

when the remote side of a socket (here, your flash client) is closed, the recv() call on the local side (here, your python server) will return an empty string (''). there is no need to continue processing, since the client won't send anything more: the channel is closed.

on the other hand, since your socket is non-blocking, if a socket timeout occurs because the client does not send any data within the specified time limit (10 seconds), then the recv() call will raise a socket.timeout exception, which you can catch and process accordingly.

you should add a test after the recv() call:

bytesRecived = sock.recv(64)
if not len(bytesRecived):
    raise InvalidSessionException('connection reset')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜