写一段socket python客户端 和 服务端 发送文件
时间: 2024-11-03 08:18:51 浏览: 21
利用socket实现客户端服务器之间简单通信
在Python中,你可以使用socket模块来创建一个简单的TCP服务器和客户端,用于发送文件。这里有一个基本的例子,包括服务端接收文件和客户端发送文件。
**服务端(server.py):**
```python
import socket
import os
def start_server():
# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8000))
server_socket.listen(1)
print("Server is listening on port 8000...")
while True:
client_connection, addr = server_socket.accept()
print(f"Connection from {addr} accepted.")
file_path = input("Enter the path of the file to be sent: ")
if not os.path.exists(file_path):
print("File does not exist.")
continue
with open(file_path, 'rb') as file:
data = file.read()
# 发送文件长度
client_connection.send(str(len(data)).encode())
# 发送文件内容
client_connection.sendall(data)
print(f"Succesfully sent file {file_path}")
client_connection.close()
if __name__ == "__main__":
start_server()
```
**客户端(client.py):**
```python
import socket
import sys
def send_file_to_server(file_path, server_address):
# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_address)
try:
# 获取文件大小并发送
with open(file_path, 'rb') as file:
file_size = os.fstat(file.fileno()).st_size
client_socket.send(str(file_size).encode())
# 发送文件内容
with open(file_path, 'rb') as file:
data = file.read()
client_socket.sendall(data)
print(f"Sent file {file_path} to server.")
except Exception as e:
print(f"Error sending file: {e}")
finally:
client_socket.close()
if __name__ == "__main__":
server_address = ('localhost', 8000) # 服务端地址
file_path = sys.argv[1] if len(sys.argv) > 1 else "test.txt"
send_file_to_server(file_path, server_address)
```
要在命令行运行客户端,你需要提供一个文件路径作为参数,例如:
```
python client.py test.txt
```
然后在另一个终端启动服务端:
```
python server.py
```
注意这只是一个基础示例,实际应用中你可能需要处理更多的边界情况,并添加错误处理。此外,为了更安全地传输文件,可以考虑使用SSL/TLS加密连接。
阅读全文