2010-09-05 48 views

回答

3

從Python的插座模塊:http://docs.python.org/library/socket.html

最初,所有插座是否阻塞 模式。在非阻塞模式下,如果一個 recv()調用未找到任何數據,或者 如果send()調用不能立即 處置該數據,則將產生一個錯誤異常

錯誤例外它指的是errno.EWOULDBLOCK

爲了做到這一點,Socket對象必須設置爲非阻塞模式下使用:socketObj.setblocking(0)

2

注意EWOULDBLOCK是錯誤號11 :

In [80]: import errno 
In [83]: errno.EWOULDBLOCK 
Out[84]: 11 

和相關的錯誤信息是:

In [86]: import os 
In [87]: os.strerror(errno.EWOULDBLOCK) 
Out[89]: 'Resource temporarily unavailable' 

以下是一些展示EWOULDBLOCK錯誤的玩具代碼。 它設置了一個服務器和客戶端,它們試圖通過套接字連接彼此通信。當調用s.setblocking(0)以將套接字置於非阻塞模式時,隨後調用s.recv將產生socket.error。我想,這是因爲連接的兩端都試圖接收數據:

import socket 
import multiprocessing as mp 
import sys 
import time 

def server(): 
    HOST='localhost' 
    PORT=6000 
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.bind((HOST, PORT)) 
    s.listen(1) 
    conn, addr=s.accept() 
    while True: 
     data=conn.recv(1024) 
     if data: 
      conn.send(data) 
    conn.close() 
def client(): 
    HOST='localhost' 
    PORT=6000 
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((HOST, PORT)) 
    s.setblocking(0)  # Comment this out, and the EWOULDBLOCK error goes away 
    s.send('Hello, world') 
    try: 
     data=s.recv(1024) 
    except socket.error as err: 
     print(err) 
     # [Errno 11] Resource temporarily unavailable 
     sys.exit() 
    finally: 
     s.close() 
    print('Received {0}'.format(repr(data))) 
def run(): 
    server_process=mp.Process(target=server) 
    server_process.daemon=True 
    server_process.start() 
    time.sleep(0.1) 
    client() 
run() 

如果s.setblocking(0)被註釋掉的,你應該看到

Received 'Hello, world' 
相關問題