python3实现CS架构文件传输

1、目标:

    基于tcp实现CS架构的文件传输

    指令列表:(1)get:从服务器端下载文件

                    (2)put:向服务器端上传文件

                    (3)list:获得服务器端的目录

2、socket模块函数:

    (1)send和sendall:send的作用是发送TCP数据,返回发送的数据大小。send函数不保证将所有数据全部发送,因此可能需要重复多次才能完成所有数据的发送。sendall的作用是发送完整的TCP数据,成功时返回None,失败时抛出异常

    (2)bind:在服务器端使用,用于将socket绑定在一个特定的ip地址和端口上。在《UNIX网络编程》一书中提到,如果调用connect或者listen之前没有bind一个特定的端口,内核会为相应的套接字分配一个随机的端口。因此,在客户端调用connect函数之前不需要bind

    (3)listen:通过参数设定服务器端最多可以接受几个客户端的连接,但是只有在完成与第一个客户端的传送后才会进行与第二个客户端的传送

3、代码:

    (1)服务器端:

    

  1. import socket  
  2. import os  
  3. import sys  
  4. import time  
  5.   
  6. Host = '127.0.0.1'  
  7. Port = 12000  
  8. Addr = (Host, Port)  
  9.   
  10. sockListener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  11. sockListener.bind(Addr)  
  12. sockListener.listen(5)  
  13.   
  14. def recvfile(cliSocket):  
  15.     print('start reveiving file...')  
  16.     msg = 'no problem'  
  17.     msg_utf8 = msg.encode(encoding="utf-8")  
  18.     cliSocket.send(msg_utf8)  
  19.     filename_utf8 = clientSocket.recv(4096)  
  20.     filename = filename_utf8.decode()  
  21.     f = open(filename, 'wb')  
  22.     while True:  
  23.         data_utf8 = cliSocket.recv(4096)  
  24.         data = data_utf8.decode()  
  25.         if data=='EOF':  
  26.             print('received file successfully')  
  27.             break  
  28.         f.write(data_utf8)  
  29.     f.close()  
  30.   
  31. def sendfile(cliSocket):  
  32.     print('start sending file...')  
  33.     msg = 'no problem'  
  34.     msg_utf8 = msg.encode(encoding="utf-8")  
  35.     cliSocket.send(msg_utf8)  
  36.     filename_utf8 = cliSocket.recv(4096)  
  37.     filename = filename_utf8.decode()  
  38.     f = open(filename, 'rb')  
  39.     while True:  
  40.         data = f.read(4096)  
  41.         if not data:  
  42.             break  
  43.         cliSocket.sendall(data)  
  44.     f.close()  
  45.     time.sleep(1)  
  46.     msg = 'EOF'  
  47.     msg_utf8 = msg.encode(encoding="utf-8")  
  48.     cliSocket.sendall(msg_utf8)  
  49.     print('sent file successfully')  
  50.   
  51. def getList(cliSocket):  
  52.     path = sys.path[0]  
  53.     every_file = os.listdir(path)  
  54.     for filename in every_file:  
  55.         pathmsg = filename + '\n'  
  56.         pathmsg_utf8 = pathmsg.encode(encoding="utf-8")  
  57.         cliSocket.sendall(pathmsg_utf8)  
  58.     time.sleep(1)  
  59.     msg = 'EOF'  
  60.     msg_utf8 = msg.encode(encoding="utf-8")  
  61.     cliSocket.sendall(msg_utf8)  
  62.     print('all filenames have been send')  
  63.   
  64. while True:  
  65.     print('waiting for connection...')  
  66.     clientSocket, addr = sockListener.accept()  
  67.     print('... connection from:', addr)  
  68.   
  69.     while True:  
  70.         msg_utf8 = clientSocket.recv(4096)  
  71.         msg = msg_utf8.decode()  
  72.         if msg=='exit':  
  73.             print(addr, 'close the connection')  
  74.             break  
  75.         elif msg=='get':  
  76.             sendfile(clientSocket)  
  77.         elif msg=='put':  
  78.             recvfile(clientSocket)  
  79.         elif msg=='list':  
  80.             getList(clientSocket)  
  81.         else:  
  82.             print('client error!')  
  83.             break  

    (2)客户端:

  1. import socket  
  2. import time  
  3.   
  4. Host = '127.0.0.1'  
  5. Port = 12000  
  6. Addr = (Host, Port)  
  7.   
  8. clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  9. clientSocket.connect(Addr)  
  10.   
  11. def recvfile(filename):  
  12.     print('start receiving file...')  
  13.     f = open(filename, 'wb')  
  14.     filename_utf8 = filename.encode(encoding="utf-8")  
  15.     clientSocket.sendall(filename_utf8)  
  16.     while True:  
  17.         data_utf8 = clientSocket.recv(4096)  
  18.         data=data_utf8.decode()  
  19.         if data=='EOF':  
  20.             print('receive file successfully')  
  21.             break  
  22.         f.write(data_utf8)  
  23.     f.close()  
  24.   
  25. def sendfile(filename):  
  26.     print('start sending file...')  
  27.     f = open(filename, 'rb')  
  28.     filename_utf8 = filename.encode(encoding="utf-8")  
  29.     clientSocket.sendall(filename_utf8)  
  30.     while True:  
  31.         data = f.read(4096)  
  32.         if not data:  
  33.             break  
  34.         clientSocket.sendall(data)  
  35.     f.close()  
  36.     time.sleep(1)  
  37.     endmsg = 'EOF'  
  38.     endmsg_utf8 = endmsg.encode(encoding="utf-8")  
  39.     clientSocket.sendall(endmsg_utf8)  
  40.     print('send file successfully')  
  41.   
  42. def confirm(confirm_command):  
  43.     confirm_command_utf8 = confirm_command.encode(encoding="utf-8")  
  44.     clientSocket.sendall(confirm_command_utf8)  
  45.     msg_utf8 = clientSocket.recv(4096)  
  46.     msg = msg_utf8.decode()  
  47.     print('reveive message:', msg)  
  48.     if msg=='no problem':  
  49.         return True  
  50.     else:  
  51.         return False  
  52.   
  53. def operation1(filename):  
  54.     if confirm('get'):  
  55.         recvfile(filename)  
  56.     else:  
  57.         print('serve error!')  
  58.   
  59. def operation2(filename):  
  60.     if confirm('put'):  
  61.         sendfile(filename)  
  62.     else:  
  63.         print('serve error!')  
  64.   
  65. def operation3(act):  
  66.     if act=='list':  
  67.         act_utf8 = act.encode(encoding="utf-8")  
  68.         clientSocket.sendall(act_utf8)  
  69.         while True:  
  70.             msg_utf8 = clientSocket.recv(1024)  
  71.             msg = msg_utf8.decode()  
  72.             if msg=='EOF':  
  73.                 break  
  74.             print(msg)  
  75.     else:  
  76.         print('wrong command!')  
  77. try:  
  78.     while True:  
  79.         command = input('>>>')  
  80.         if not command:  
  81.             continue  
  82.         elif command=='exit':  
  83.             command_utf8 = command.encode(encoding="utf-8")  
  84.             clientSocket.sendall(command_utf8)  
  85.             print('the connection is closed')  
  86.             break  
  87.         msg = command.split()  
  88.         if len(msg)==2 and msg[0]=='get':  
  89.             operation1(msg[1])  
  90.         elif len(msg)==2 and msg[0]=='put':  
  91.             operation2(msg[1])  
  92.         elif len(msg)==1:  
  93.             operation3(msg[0])  
  94.         else:  
  95.             print('wrong command!')  
  96. except socket.error as e:  
  97.     print('error:', e)  
  98.     print('an error causes the connection to close!')  
  99.     clientSocket.close()  

猜你喜欢

转载自blog.csdn.net/N_Young/article/details/79966386