用python实现基于TCP协议的文件传输系统:设计一个可以实现文件上传和下载的系统,利用TCP协议进行数据传输,包括客户端和服务器端的实现。
时间: 2024-03-06 20:49:37 浏览: 46
以下是一个基于TCP协议的文件传输系统的Python实现,包括客户端和服务器端的代码。
服务器端代码:
```python
import socket
# 定义服务器地址和端口号
ip_port = ('127.0.0.1', 8888)
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址
server_socket.bind(ip_port)
# 监听连接
server_socket.listen(5)
print('服务器已启动,等待客户端连接...')
while True:
# 接受客户端连接
conn, addr = server_socket.accept()
# 接收客户端请求
data = conn.recv(1024).decode()
if data == 'upload':
# 接收客户端上传的文件
with open('server_upload.txt', 'wb') as f:
while True:
file_data = conn.recv(1024)
if not file_data:
break
f.write(file_data)
print('文件上传成功!')
elif data == 'download':
# 发送文件给客户端
with open('server_upload.txt', 'rb') as f:
file_data = f.read()
conn.sendall(file_data)
print('文件发送成功!')
# 关闭连接
conn.close()
```
客户端代码:
```python
import socket
# 定义服务器地址和端口号
ip_port = ('127.0.0.1', 8888)
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(ip_port)
# 请求上传文件
client_socket.send('upload'.encode())
# 上传文件
with open('client_upload.txt', 'rb') as f:
file_data = f.read()
client_socket.sendall(file_data)
print('文件上传成功!')
# 请求下载文件
client_socket.send('download'.encode())
# 接收文件
with open('client_download.txt', 'wb') as f:
while True:
file_data = client_socket.recv(1024)
if not file_data:
break
f.write(file_data)
print('文件下载成功!')
# 关闭连接
client_socket.close()
```
运行以上代码后,客户端会将本地的`client_upload.txt`文件上传至服务器,并将服务器上的`server_upload.txt`文件下载到本地的`client_download.txt`文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)