Python中send和sendall的區別


官方文檔對socket模式下的socket.send() 和 socket.sendall()解釋如下:

sock.sendall(string[, flags])

        Send data to the socket. The socket must be connected  to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occure. None is returned on success. On error, an exception is raised, and there is no way to datermine how much data, if any, was successfully sent.

       嘗試發送string的所有數據, 成功則返回None, 失敗則拋出異常。

 

socket.send(string [, flags])

       Send data to the socket.  The socket must be connected to a remote socket.  The optional flags argument has the same meaning as for recv() above. Returns the number of bytes snet. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data.

       send()的返回值式發送的字節數量, 這個數量值可能小於要發送的string的字節數,也就是說可能無法發送string中所有的數據。如果有錯誤,則會拋出異常。

所以, 下面兩段代碼是等價的:

sock.sendall("Hello world\n")

 

buffer = "Hello world\n"
while buffer:
    bytes = sock.send(buffer)
    buffer = buffer[bytes:]

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM