python 客户端socket传输文件,服务端接收并返回收到
时间: 2024-09-25 22:18:30 浏览: 52
python网络编程socket实现服务端、客户端操作详解
在Python中,客户端通过Socket套接字可以发送文件到服务器。首先,你需要创建一个TCP套接字,并连接到服务器。然后,可以使用`sendfile()`函数发送整个文件,而不是逐行或字节发送,这会更高效。下面是一个简单的示例:
**客户端(client.py):**
```python
import socket
def send_file_to_server(file_path, server_ip, server_port):
with open(file_path, 'rb') as file:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
try:
total_sent = 0
sent = client_socket.sendfile(file, offset=total_sent)
while sent > 0:
total_sent += sent
print(f"Sent {total_sent} bytes")
sent = client_socket.sendfile(file, offset=total_sent)
finally:
client_socket.close()
print("File transmission complete.")
# 使用示例
send_file_to_server('path/to/your/file', 'server_ip', server_port)
```
**服务端(server.py):**
```python
import socket
from os import rename, path
def handle_client(client_socket):
request = client_socket.recv(1024).decode()
# 从请求中获取文件名
file_name = request.split('/')[-1]
# 创建一个临时文件保存接收的数据
temp_file_path = "received_" + file_name
with open(temp_file_path, 'wb') as file:
chunk_size = 1024
while True:
data = client_socket.recv(chunk_size)
if not data:
break
file.write(data)
# 将数据写入最终文件并关闭
with open(file_name, 'wb') as dest_file:
dest_file.write(open(temp_file_path, 'rb').read())
rename(temp_file_path, file_name)
client_socket.sendall("File received successfully".encode())
client_socket.close()
if __name__ == "__main__":
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('server_ip', server_port))
server_socket.listen()
print("Server is listening...")
while True:
client_connection, addr = server_socket.accept()
print(f"Accepted connection from: {addr}")
handle_client(client_connection)
```
**相关问题--:**
1. 服务端如何确认文件已成功接收?
2. 如果文件传输过程中网络中断,该如何处理?
3. 在并发情况下,如何改进服务端以更好地处理多个客户端请求?
阅读全文