用python实现发文件和收文件
时间: 2024-03-27 15:39:55 浏览: 13
你好,以下是用Python实现发送文件和接收文件的示例代码:
1. 发送文件
```python
import socket
def send_file(filename, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
with open(filename, 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
sock.sendall(data)
sock.close()
```
使用示例:
```python
send_file('test.txt', '127.0.0.1', 8888)
```
2. 接收文件
```python
import socket
def receive_file(filename, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1)
conn, addr = sock.accept()
with open(filename, 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
conn.close()
sock.close()
```
使用示例:
```python
receive_file('test.txt', '127.0.0.1', 8888)
```
注意:在使用时需要保证发送端和接收端的host和port参数一致。