python局域网传输文件
时间: 2023-07-31 11:11:21 浏览: 225
基于局域网的文件传输python
可以使用 Python 的 socket 模块来进行局域网文件传输。以下是一个简单的示例:
服务端代码(server.py):
```python
import socket
HOST = ''
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Waiting for connection...')
conn, addr = s.accept()
print('Connected by', addr)
with conn:
filename = conn.recv(1024).decode()
with open(filename, 'wb') as f:
print('Receiving data...')
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print('File received.')
```
客户端代码(client.py):
```python
import socket
HOST = '192.168.1.2' # 服务端 IP 地址
PORT = 5000
filename = 'test.txt'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(filename.encode())
with open(filename, 'rb') as f:
print('Sending data...')
while True:
data = f.read(1024)
if not data:
break
s.sendall(data)
print('File sent.')
```
注意,这里的服务端 IP 地址需要替换为实际的 IP 地址。同时,客户端和服务端都需要运行在局域网内,否则无法建立连接。
阅读全文