使用Python的Connection()函数进行文件传输
发布时间:2023-12-19 06:41:20
使用Python的Connection()函数进行文件传输需要使用socket模块。下面是一个使用例子,包括一个发送端和接收端的示例代码。
发送端代码:
import socket
def send_file(file_path, host, port):
# 创建一个TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到接收端的地址和端口
server_address = (host, port)
print(f'连接到 {server_address}')
sock.connect(server_address)
try:
# 打开要发送的文件
file = open(file_path, 'rb')
# 读取文件内容并发送给接收端
data = file.read(1024)
while data:
print(f'发送 {data}')
sock.sendall(data)
data = file.read(1024)
# 发送完毕后关闭连接
print('发送完毕')
sock.shutdown(socket.SHUT_WR)
sock.close()
except IOError as e:
print(f'发送文件失败: {e}')
finally:
sock.close()
# 要发送的文件路径
file_path = 'path/to/file.txt'
# 接收端的地址和端口
host = 'example.com'
port = 12345
# 发送文件
send_file(file_path, host, port)
接收端代码:
import socket
def receive_file(save_path, host, port):
# 创建一个TCP/IP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定套接字到地址和端口
server_address = (host, port)
print(f'开始监听 {server_address}')
sock.bind(server_address)
# 监听连接
sock.listen(1)
while True:
print('等待连接...')
connection, client_address = sock.accept()
print(f'已连接: {client_address}')
try:
# 打开要保存的文件
file = open(save_path, 'wb')
# 从发送端接收文件内容并保存
data = connection.recv(1024)
while data:
print(f'接收 {data}')
file.write(data)
data = connection.recv(1024)
# 接收完毕后关闭连接
print('接收完毕')
file.close()
connection.close()
break
except IOError as e:
print(f'接收文件失败: {e}')
finally:
file.close()
connection.close()
# 要保存文件的路径
save_path = 'path/to/save/file.txt'
# 接收端的地址和端口
host = 'example.com'
port = 12345
# 接收文件
receive_file(save_path, host, port)
以上代码演示了如何使用Python的Connection()函数进行文件传输。发送端通过Socket建立与接收端的连接,读取要发送的文件,并发送文件内容。接收端通过Socket监听连接,接收发送端发送的文件内容,并保存到指定的位置。需要注意的是,发送端和接收端需要连接到相同的主机和端口。
