上面的代码如何实现双向文件传输呢,举几个例子
时间: 2023-07-16 12:13:48 浏览: 127
实现双向文件传输可以借助 socket 编程中的 send() 和 recv() 函数,以及文件读写操作。以下是两个例子:
1. 客户端向服务器传输文件
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
with open('client_file.txt', 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
s.sendall(data)
print('File sent successfully')
```
服务器端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with open('server_file.txt', 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print('File received successfully')
```
2. 服务器向客户端传输文件
服务器端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with open('server_file.txt', 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
conn.sendall(data)
print('File sent successfully')
```
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
with open('client_file.txt', 'wb') as f:
while True:
data = s.recv(1024)
if not data:
break
f.write(data)
print('File received successfully')
```
以上两个例子中,客户端和服务器端都可以进行文件的读写操作,从而实现双向文件传输。需要注意的是,文件传输过程中需要将文件按照固定大小进行分割,以便传输和接收。在这里,我们使用了每次读写 1024 字节的方式。
阅读全文