socket.send()和socket.sendall()有什么区别?

2024-06-16 11:08:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python中的socket.send()socket.sendall()函数感到困惑。据我从the documentationsend()了解,函数使用TCP协议,而sendall()函数使用UDP协议发送数据。我知道TCP对于大多数Web应用程序来说更可靠,因为我们可以检查哪些包被发送,哪些包不被发送。这就是为什么,我认为使用send()函数比使用sendall()函数更可靠。

在这一点上,我想问一下这两个函数之间的确切区别是什么,哪一个对于web应用程序更可靠?

谢谢你。


Tags: the函数sendweb应用程序协议socket发送数据
1条回答
网友
1楼 · 发布于 2024-06-16 11:08:52

socket.send是一个低级方法,基本上只是C/syscall方法send(3)/send(2)。它可以发送比您请求的更少的字节,但返回发送的字节数。

socket.sendall是一个高级的Python-only方法,它发送传递或引发异常的整个缓冲区。它通过调用socket.send来实现这一点,直到发送完所有内容或发生错误。

如果你使用TCP来阻塞套接字,并且不想被打扰 按内部(对于大多数简单的网络应用程序来说是这样的), 使用sendall。

以及python文档:

Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent

感谢菲利普·哈格梅斯特对我过去的简要描述。

编辑

sendall在引擎盖下使用send-查看cpython实现。下面是作用(或多或少)类似于sendall的示例函数:

def sendall(sock, data, flags=0):
    ret = sock.send(data, flags)
    if ret > 0:
        return sendall(sock, data[ret:], flags)
    else:
        return None

或来自rpython (pypy source)

def sendall(self, data, flags=0, signal_checker=None):
    """Send a data string to the socket.  For the optional flags
    argument, see the Unix manual.  This calls send() repeatedly
    until all data is sent.  If an error occurs, it's impossible
    to tell how much data has been sent."""
    with rffi.scoped_nonmovingbuffer(data) as dataptr:
        remaining = len(data)
        p = dataptr
        while remaining > 0:
            try:
                res = self.send_raw(p, remaining, flags)
                p = rffi.ptradd(p, res)
                remaining -= res
            except CSocketError, e:
                if e.errno != _c.EINTR:
                    raise
            if signal_checker is not None:
                signal_checker()

相关问题 更多 >