def check_id(self): ''' check id package must like ------------------------------- post handshake msw/0.1 id: [yourID] listen_port: [3900] length: 0 ------------------------------- error code list: 1: not get "id" in head 2: receive data failed 3: appname is not handshake 4: id is yourself ''' data = None if self.positive: self.send_id() try: data = self.conn.recv(BUFFSIZE) except ConnectionResetError: print('One connection failed before ID check') if not data: return 2, '' self.buff += data dp = Datapack() dp.encode_data = self.buff # maybe here needs to use copy.copy(self.buff) self.buff = dp.decode(only_head=True) if not dp.head.get('id'): return 1, dp.head.get('flag') if not dp.app == 'handshake': return 3, dp.head.get('flag') self.id = dp.head['id'] self.listen_port = int(dp.head.get('listen_port')) if self.id == ID: #print('you connect to your self') return 4, dp.head.get('flag') if ONLYPROXY and not self.id == MYPROXY: # refuce not proxy connection return 5, dp.head.get('flag') if dp.head.get('onlyuseproxy'): if not dp.head['onlyuseproxy'] == ID: return 6, dp.head.get('flag') if not self.positive: self.send_id() return 0, dp.head.get('flag')
def receive(self): still_need = 0 while True: try: data = self.conn.recv(BUFFSIZE) except ConnectionResetError: break except Exception as e: print('Connection recv error %s: %s' % (type(e), str(e))) break if not data: break self.buff += data if not still_need: dp = Datapack() dp.encode_data = self.buff try: self.buff = dp.decode(only_head=True) if dp.method == 'file': create_floder(dp.head['filename']) create_floder('tmp/' + dp.head['filename']) self.f = open('tmp/' + dp.head['filename'], 'ab') if dp.method == 'file' and os.path.exists(dp.head['filename']): os.remove(dp.head['filename']) except Exception as e: print('Decode head failed %s: %s' % (type(e), str(e))) print(self.buff) break length = int(dp.head.get('length')) still_need = length if still_need > len(self.buff): # writing tmp data if dp.method == 'file': still_need -= self.f.write(self.buff) else: dp.body += self.buff still_need -= len(self.buff) self.buff = b'' # empty buff because all tmp data has been write else: # download complete setuation if dp.method == 'file': self.f.write(self.buff[:still_need]) self.f.close() self.f = None else: dp.body = self.buff[:still_need] self.buff = self.buff[still_need:] still_need = 0 # bleow code are using to process datapack if dp.method == 'file': os.rename('tmp/' + dp.head['filename'], dp.head['filename']) print('Received file %s from %s' % (dp.head['filename'], self.id), dp) send_queue.put(dp) # below code are using to closed connection if self.f: self.f.close() self.f = None self.conn.close() self.netowrk_controller.del_connection(self)