034文件上传

因为这个是简单的,所以很容易
思想就是建立连接后,客户端发送文件名字和大小到服务端,服务端接受后,客户端开始发送文件,直到发完。具体的还是要看下面的代码,我自己实现了一遍

 1 import  socket
 2 import  os
 3 
 4 def get_server_socket():
 5     sk = socket.socket()
 6     address = ('127.0.0.1',8888)
 7     sk.bind(address)
 8     sk.listen(3)
 9     return sk
10 
11 def  wait_connect(sk):
12     print('waitconnecting...')
13     conn, addr = sk.accept()
14     return conn
15 
16 if  __name__ == '__main__':
17     sk = get_server_socket()
18     conn = wait_connect(sk)
19     BASIC_DIR = os.path.dirname(os.path.abspath(__file__))
20     while True:
21         data = str(conn.recv(1024),'utf8')
22         cmd,filename,file_size = data.split('|')
23         path = os.path.join(BASIC_DIR,'yuan',filename)
24         file_size = int(file_size)
25     f = open(path,'wb')
26     has_receive = 0
27     while has_receive != file_size:
28         data = conn.recv(1024)
29         f.write(data)
30         has_receive += len(data)
31     f.close()
post_server.py
 1 import  socket
 2 import  os
 3 
 4 def  get_client_socket():
 5     sk = socket.socket()
 6     address = ('127.0.0.1',8888)
 7     sk.connect(address)
 8     return sk
 9 
10 if __name__ == '__main__':
11     BASIC_DIR = os.path.dirname(os.path.abspath(__file__))
12     sk = get_client_socket()
13     while  True:
14         inp = input('>>>').strip()#post|11.png
15         cmd,path = inp.split('|')
16         path = os.path.join(BASIC_DIR,path)#使用系统的路径拼接
17         filename = os.path.basename(path)#拿到文件名字
18         file_size = os.stat(filename).st_size#拿到文件的大小
19         file_info = 'post|%s|%s'%(filename,file_size)
20         sk.sendall(bytes(file_info,'utf8'))
21     f = open(path,'rb')
22     has_sent = 0
23     while has_sent != file_size:
24         data = f.read(1024)
25         sk.sendall(data)
26         has_sent += len(data)
27     f.close()
28     print('上传完成')
post_client.py

 

posted @ 2018-03-04 12:00  Alos403  阅读(114)  评论(0编辑  收藏