Python socket库send()和sendall()区别

在Python的socket模块中,send()sendall()方法都用于发送数据。

  1. send()方法:
    • send()方法尝试发送指定数量的字节。
    • 如果返回的字节数少于请求的字节数,需要多次调用send()来发送剩余的数据。
    • send() 方法返回一个整数,表示实际已发送的字节数。这个数字可能小于请求发送的字节数,特别是在非阻塞模式下,或者当网络拥塞时。

  2. sendall()方法:
    • sendall()方法尝试发送所有指定的数据,直到所有数据都被成功发送或发生错误。
    • 它是一个阻塞操作,意味着在数据完全发送之前,调用线程将被阻塞。
    • sendall() 方法的返回值是 None,或者在发生错误时抛出异常。由于 sendall() 会确保所有数据都被发送,因此不需要返回实际发送的字节数。

import socket  
  
# 创建一个TCP/IP套接字  
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  
# 连接到服务器
server_address = ('localhost', 10000)  
sock.connect(server_address)  
  
try:  
    # 使用send()方法发送数据  
    message = b'This is a message using send().'  
    print('Sending {!r}'.format(message))  
    sent = sock.send(message)  
    print('Sent {!r}'.format(sent))  # 可能会少于message的长度  
  
    # 使用sendall()方法发送数据  
    message = b'This is a message using sendall().'  
    print('Sending {!r}'.format(message))  
    sock.sendall(message)  
    print('All data sent.')  # sendall()保证所有数据都被发送  
  
finally:  
    print('Closing socket')  
    sock.close()

使用 send() 方法并确定每次发送的数据量:。否则,我们。 

import socket  
  
# 创建一个TCP/IP套接字  
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  
# 连接到服务器  
server_address = ('localhost', 12345)  
sock.connect(server_address)  
  
try:  
    # 要发送的数据  
    data = b'This is the data to send'  
    total_sent = 0  # 记录已发送的数据总量  
  
    # 通过一个循环来确保所有数据都被发送 
    while total_sent < len(data):  
        # 调用 send() 方法并更新 total_sent 变量来跟踪已发送的数据量 
        sent = sock.send(data[total_sent:])  
        # 如果 send() 方法返回0,这意味着套接字连接已断开,抛出一个异常
        if sent == 0:  
            raise RuntimeError("Socket connection broken")  
        total_sent += sent  
        #打印出每次发送的字节数和总共发送的字节数
        print(f"Sent {sent} bytes, total {total_sent} bytes")  
  
finally:  
    print('Closing socket')  
    sock.close()
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值