day47——使用 Socket 实现 FTP Server

Posted 落后乞丐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day47——使用 Socket 实现 FTP Server相关的知识,希望对你有一定的参考价值。

使用 Socket 实现 FTP Server ,实现如下功能:

get  /tmp/1.txt  /tmp/1.txt :把服务端 /tmp/1.txt 下载到客户端 /tmp/1.txt
put  /tmp/1.txt  /tmp/1.txt :把客户端 /tmp/1.txt 上传到服务端 /tmp/1.txt

 1 [[email protected] ~]# cat ftp_server.py 
 2 #!/usr/bin/env python
 3 #-*- coding: utf8 -*-
 4 
 5 import socket
 6 from subprocess import Popen, PIPE
 7 
 8 HOST = ‘‘
 9 PORT = 1234
10 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 s.bind((HOST, PORT))
12 s.listen(1)
13 conn, addr = s.accept()
14 print conn, conn
15 print Connected by, addr
16 while 1:
17     cmd = conn.recv(1024)
18     cmd_list = cmd.split()
19     if cmd_list[0] == get:
20         with open(cmd_list[1]) as fd:
21             while True:
22                 data = fd.read(1024)
23                 conn.sendall(data)
24                 if not data:
25                     conn.sendall(EOF)
26                     break
27     if not cmd: break
28 conn.close()
 1 [[email protected] ~]# cat ftp_client.py 
 2 #!/usr/bin/env python
 3 #-*- coding:utf-8 -*-
 4 
 5 import os
 6 import sys
 7 import tab
 8 import socket
 9 
10 HOST = 192.168.5.131
11 PORT = 1234
12 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13 s.connect((HOST, PORT))
14 while True:
15     cmd = raw_input("Please input cmd: ").strip()
16     if cmd.lower()== exit or cmd.lower() == quit:
17         break
18     cmd_list = cmd.split()
19     if len(cmd_list) != 3:
20         print "Ex: get file1 file2"
21         continue
22     else:
23         s.sendall(cmd)
24         if not os.path.exists(cmd_list[2]):
25             dst_file = cmd_list[2]
26         else:
27             dst_file = cmd_list[2]+.new
28         n = 1
29         while True:
30             data_rev = s.recv(1024)
31             if data_rev.endswith(EOF):
32                 data = data_rev[:-3]
33             else:
34                 data = data_rev
35             if n == 1:
36                 with open(dst_file, wb) as fd:
37                     fd.write(data) 
38             else:
39                 with open(dst_file, a) as fd:
40                     fd.write(data)
41             n += 1
42             if data_rev[-3:] == EOF:
43                 print "Success! destination file is %s" % dst_file
44                 break
45 s.close()

 

以上是关于day47——使用 Socket 实现 FTP Server的主要内容,如果未能解决你的问题,请参考以下文章

c#C/S实现文件的上传下载

PYTHON学习笔记-DAY-8

Python全栈开发-Day8-Socket网络编程

python_day8 网络编程 socket

使用 Socket 实现 FTP Server

c# c/s结构Socket上传文件的代码