socket编程二十二:socket编程实现文件传输功能
时间: 2023-11-17 07:08:52 浏览: 208
好的,针对您的问题,可以通过以下步骤实现socket编程实现文件传输功能:
1. 服务端创建socket并绑定IP地址和端口号;
2. 服务端监听客户端的连接请求;
3. 客户端创建socket并连接到服务端;
4. 客户端读取本地文件并将文件内容发送给服务端;
5. 服务端接收客户端发送的文件内容并保存到本地。
以下是一个简单的示例代码:
服务端:
```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 conn:
print('Connected by', addr)
with open('received_file.txt', 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print('File received 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('file_to_send.txt', 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
s.sendall(data)
print('File sent successfully')
```
阅读全文