标签:客户端 out receive sleep except span lock ble pen
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: xuexueuxe import socket import select import os,json,time,queue def get(r,cmd): filename = cmd.split()[1] filesize = os.stat(filename).st_size msg_dic = {"filesize": filesize} r.send(json.dumps(msg_dic).encode()) file = open("%s" % filename, "rb") for line in file: r.send(line) else: print("get%s" % file) file.close() print("处理完成") def put(r,cmd): while True: filename = cmd.split()[1] file_size = 0 try: msg_dic = json.loads(r.recv(1024).decode()) receive_size = msg_dic["filesize"] print(receive_size) file = open("%s.new" % filename, "wb") while receive_size > file_size: data =r.recv(1024) file.write(data)#因为没写完,所以改一下 time.sleep(0.001) file_size +=len(data) print(file_size) else: print("put success") file.close() except Exception as e: continue def ftp_server():#主程序 server =socket.socket() server.bind((‘localhost‘,9999)) server.listen(1024) server.setblocking(False) inputs = [server] outputs = [] ms_dic = {} while True: readable,writeable,exceptional = select.select(inputs,outputs,inputs) for r in readable: if r is server: conn,addr = r.accept() print("连上客户端",addr) inputs.append(conn) ms_dic[conn] = queue.Queue() else: try: while True: cmd =r.recv(1024).decode() if cmd: cmd_str = cmd.split()[0] if cmd_str == ‘get‘: get(r,cmd) if cmd_str == ‘put‘: put(r,cmd) except Exception as e : continue if __name__ == ‘__main__‘: print("服务端口启动") ftp_server()
#!/usr/bin/env python # -*- coding = utf-8 -*- # Autor :xuexuexue import socket,os import json client=socket.socket()#声明socket类型同时生成socket链接对象 client.connect((‘localhost‘,9999)) while True: file = input(">>:") client.send(file.encode()) if len(file) == 0: print("请重新输入:") continue cmd = file.split()[0] if cmd == ‘get‘: filename = file.split()[1] file_size = 0 msg_dic = json.loads(client.recv(1024).decode()) receive_size = msg_dic["filesize"] print(receive_size) file = open("%s.new"%filename, "wb") while receive_size > file_size: data = client.recv(1024) file.write(data) file_size += len(data) else: print("get success") file.close() if cmd == ‘put‘: filename = file.split()[1] filesize = os.stat(filename).st_size print(filesize) msg_dic = {"filesize": filesize} client.send(json.dumps(msg_dic).encode()) file = open("%s"%filename,"rb") for line in file: client.send(line) else: print("put%s" %file) file.close()
标签:客户端 out receive sleep except span lock ble pen
原文地址:https://www.cnblogs.com/xuexiexue/p/12859178.html