使用socket编程,用python实现一个FTP服务器和客户端
时间: 2024-03-05 18:53:21 浏览: 111
好的,我可以为您提供一个简单的FTP服务器和客户端的Python代码示例,您可以根据您的需求进行修改和完善。
FTP服务器代码:
```python
import socket
import os
def serve():
server_socket = socket.socket()
server_socket.bind(('localhost', 8000))
server_socket.listen(5)
print('FTP server started, waiting for connections...')
while True:
conn, addr = server_socket.accept()
print('Connected by ', addr)
while True:
data = conn.recv(1024).decode()
if not data:
break
cmd = data.split()[0]
if cmd == 'LIST':
files = os.listdir('.')
conn.sendall('\n'.join(files).encode())
elif cmd == 'RETR':
filename = data.split()[1]
if os.path.isfile(filename):
with open(filename, 'rb') as f:
content = f.read()
conn.sendall(content)
else:
conn.sendall('File not found'.encode())
conn.close()
if __name__ == '__main__':
serve()
```
FTP客户端代码:
```python
import socket
def get_file_list():
client_socket = socket.socket()
client_socket.connect(('localhost', 8000))
client_socket.sendall('LIST'.encode())
data = client_socket.recv(1024).decode()
print('File list:')
print(data)
client_socket.close()
def download_file(filename):
client_socket = socket.socket()
client_socket.connect(('localhost', 8000))
client_socket.sendall(('RETR ' + filename).encode())
content = client_socket.recv(1024)
with open(filename, 'wb') as f:
while content:
f.write(content)
content = client_socket.recv(1024)
print('Downloaded file:', filename)
client_socket.close()
if __name__ == '__main__':
get_file_list()
download_file('file.txt')
```
这个简单的FTP服务器和客户端实现了两个命令:LIST 和 RETR。LIST 命令列出当前目录下的所有文件,RETR 命令下载指定的文件。在客户端中,您可以根据您的需求修改和添加其他命令。
阅读全文