2012-11-10 41 views
3

我注意到,在Python中編程一個TCP服務器時,當一端或另一端意外停止時,在不同情況下會發生一些錯誤。例如,有時我得到了「管道破損」(errno.EPIPE),有時「連接中止」(errno.CONNABORTEDerrno.WSAECONNABORTED)。還有跨操作系統the codes are not the same,但我猜Python的errno模塊處理。什麼是意味着套接字連接丟失的錯誤代碼?

我搜索了很多關於套接字連接的錯誤代碼的含義列表,但沒有找到我正在尋找的東西。

我有什麼到現在爲止是這樣的:

try: 
    # write or read operation 
except socket.error as e: 
    if e.errno in (errno.EPIPE, errno.ECONNABORTED, errno.WSAECONNABORTED): 
     print 'Connection lost with server...' 

到現在爲止,一切工作順利,甚至把最後一個之前,我對Windows中的問題,並補充,所以恐怕可能有一些我沒有處理的情況。此外,有時,它只是沒有拋出一個錯誤,並保持閱讀空行(與recv)和錯誤文件描述符等。

SocketServer類提供這樣的事嗎?或一般的TCP連接?

回答

1

當您嘗試從python中的封閉套接字讀取時,通常不會引發異常。你應該閱讀直到recv返回emty字符串。

寫入一個封閉的套接字當然引發一個Execption(socket.error),它封裝了OS引發的錯誤號。

但是你不應該過多關心錯誤代碼。 Python不是C,或者如tutorial在談到非阻塞套接字時所說的那樣:

您可以檢查返回代碼和錯誤代碼,並且通常讓自己瘋狂。如果你不相信我,請嘗試一下。你的應用程序將會變得越來越大,越野車和吸CPU。所以讓我們跳過那些大腦死亡的解決方案,並做對了。

...

+0

謝謝您的鏈接,儘可能多的搜索我從來沒有看到它!我很肯定我在這兩種情況下都遇到了錯誤,但現在我閱讀了教程,我認爲這是因爲我使用了由'SocketServer'類('rfile'和'wfile')提供的緩衝讀取器......也許我會用另一種方法('recv','send',也可以在這個類中使用)。是的,我知道最好讓Python處理線程中的異常,但我認爲回溯看起來不太好,這是項目的一部分,所以我寧願自定義消息。 – jadkik94

+1

在函數正常返回後(在沒有例外的語言中,例如C),必須檢查錯誤代碼並檢查由函數調用引發的異常對象上的errno之間有區別。前者是那種容易出錯的東西,其中有例外語言的負擔試圖緩解程序員的負擔。後者基本上是必不可少的知道*發生了什麼*。在某些情況下,知道與發生的事情不同的東西就足夠了,但在大多數情況下,您實際上需要知道發生了什麼。 –

+0

謝謝你們兩位:)我會讓它失敗,然後忽略它。 – jadkik94

1

Python的插座模塊是圍繞BSD套接字API,一個最瘦包裝。通常,您可以通過查看C BSD套接字API的手冊頁找到可能的錯誤代碼(errno值)的文檔。例如,man 2 recv

ERRORS 
    These are some standard errors generated by the socket layer. Additional errors 
    may be generated and returned from the underlying protocol modules; see their 
    manual pages. 

    EAGAIN or EWOULDBLOCK 
      The socket is marked nonblocking and the receive operation would 
      block, or a receive timeout had been set and the timeout expired before 
      data was received. POSIX.1-2001 allows either error to be returned for 
      this case, and does not require these constants to have the same value, 
      so a portable application should check for both possibilities. 

    EBADF The argument sockfd is an invalid descriptor. 

    ECONNREFUSED 
      A remote host refused to allow the network connection (typically because 
      it is not running the requested service). 

    EFAULT The receive buffer pointer(s) point outside the process's address space. 

    EINTR The receive was interrupted by delivery of a signal before any data were 
      available; see signal(7). 

    EINVAL Invalid argument passed. 

    ENOMEM Could not allocate memory for recvmsg(). 

    ENOTCONN 
      The socket is associated with a connection-oriented protocol and has not 
      been connected (see connect(2) and accept(2)). 

    ENOTSOCK 
      The argument sockfd does not refer to a socket. 

的手動頁殘缺往往是自己,但它們覆蓋比任何Python文檔的更多情況。

+0

謝謝,我不知道在哪裏搜索這些內容,因爲Python文檔對我來說似乎不完整。雖然好的方法似乎是讓例外而不嘗試進一步分析。 – jadkik94

+0

我希望你會發現,直到它不是真的。 –

相關問題