Python socket库中send()和sendall()方法的区别
在Python的socket
模块中,send()
和sendall()
方法都用于发送数据。
send()
方法:send()
方法尝试发送指定数量的字节。- 如果返回的字节数少于请求的字节数,需要多次调用
send()
来发送剩余的数据。 -
send()
方法返回一个整数,表示实际已发送的字节数。这个数字可能小于请求发送的字节数,特别是在非阻塞模式下,或者当网络拥塞时。 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()
作者:YH美洲大蠊