Esempio n. 1
0
 def on_open(self):
     #
     self.url = "wss://ws-feed.gdax.com/"
     self.products = ["ETH-USD"]
     self.message_count = 0
     self.sma = bf.Buffer(5)
     self.lma = bf.Buffer(10)
Esempio n. 2
0
 def __init__(self):
     # initialize map objects
     self.car = self.MAP_BUILDER.car
     self.walls = self.MAP_BUILDER.walls
     self.rangefinder_group = sensors(self.car)
     self.center_point = self.MAP_BUILDER.point
     # initialize game variables
     self.resolution = (self.DISPLAY_WIDTH, self.DISPLAY_HEIGHT)
     self.clock = pygame.time.Clock()
     self.game_ext = False
     self.performance = 0
     self.ticks = 0
     # initialize algorithm settings
     self.network = nn3(inputcount=11, hiddencount=5, outputcount=1)
     self.mod_scheme = ModulationScheme(self.rangefinder_group, self.walls)
     self.mod_buffer = buffer.Buffer(self.network.initlen, maxlen=self.network.maxlen, \
                                     growth_fact=self.network.growth)
     # Initialize visual settings
     self.options = self.OPTIONS
     self.game_display = None
     self.font = None
     self.bounds = None
     self.calculate_bounds()
     self.network_visualizer = visualnet.NetworkVisualizer(
         self.network, [self.bounds[0], 0, 1600, self.bounds[1]])
     pygame.init()
     pygame.font.init()
 def __init__(self, *args, **kwargs):
     if kwargs:
         self.camera = kwargs.get('camera', camera.Camera())
         self.scene = kwargs.get('scene', scene.Scene())
         self.background_color = kwargs.get('background_color',
                                            glm.vec3(.0, .0, .0))
         self.samples = kwargs.get('samples', 1)
         self.buffer = kwargs.get('buffer', buffer.Buffer())
     elif args:
         self.camera, self.scene, self.background_color, self.samples, self.buffer = args
     else:
         self.camera = camera.Camera()
         self.scene = scene.Scene()
         self.background_color = glm.vec3(.0, .0, .0)
         self.samples = 1
         self.buffer = buffer.Buffer()
Esempio n. 4
0
    def test_nested(self):
        r = random.Random()
        r.seed(1356317227)

        root = buffer.Buffer(width=0, height=0)
        current = root
        all = []
        i = 0
        for sub in range(0, min(self.height, self.width), 4):
            h = self.height - sub
            w = self.width - sub
            i += 1
            b = buffer.Box(width=w,
                           height=h,
                           border_fg=(i % 16),
                           border_bg=(i + 1) % 8)
            current.children.append(b)
            all.append(b)
            current = b

        for i in range(30):
            root.draw()
            b = r.choice(all)
            for j in range(20):
                b.set_at(
                    x=r.randint(0, b.width - 1),
                    y=r.randint(0, b.height - 1),
                    char=chr(r.randint(0, 255)),
                    fg=int(r.triangular(0, 15)),
                    bg=int(r.triangular(0, 7)),
                )
            term.flip()
Esempio n. 5
0
    def test_oob_blit(self):
        nullbuff = buffer.Buffer(x=10, y=10, width=0, height=0)
        nullbuff.draw()

        whitebox = buffer.Box(x=10,
                              y=10,
                              width=5,
                              height=5,
                              interior_bg=colors.WHITE)
        redbox = buffer.Box(x=10,
                            y=10,
                            width=5,
                            height=5,
                            interior_bg=colors.RED)
        bluebox = buffer.Box(x=10,
                             y=10,
                             width=5,
                             height=5,
                             interior_bg=colors.BLUE)
        self.draw_box(whitebox)

        redbox.x = -1
        redbox.y = -1
        redbox.draw()
        term.flip()

        self.check(0, 0, bg=colors.RED)
        self.check(self.width - 1, self.height - 1, bg=colors.BLACK)

        bluebox.x = self.width - 2
        bluebox.y = self.height - 2
        bluebox.draw()
        term.flip()
        self.check(self.width - 2, self.height - 2, ch=boxtypes.BoxDouble.tl)
        self.check(self.width - 1, self.height - 1, bg=colors.BLUE)
Esempio n. 6
0
 def test_invalid_data(self):
     self.assertRaises(ValueError, buffer.Buffer, width=1, height=1, data=0)
     self.assertRaises(ValueError,
                       buffer.Buffer,
                       width=1,
                       height=1,
                       data=[])
     self.assertRaises(ValueError,
                       buffer.Buffer,
                       width=1,
                       height=1,
                       data=[0])
     self.assertRaises(ValueError,
                       buffer.Buffer,
                       width=1,
                       height=1,
                       data=[[]])
     self.assertRaises(ValueError,
                       buffer.Buffer,
                       width=1,
                       height=1,
                       data=[[0]])
     self.assertRaises(ValueError,
                       buffer.Buffer,
                       width=1,
                       height=1,
                       data=[[['a', 'b']]])
     self.assertTrue(buffer.Buffer(width=1, height=1, data=[[[0, 0, 0]]]))
Esempio n. 7
0
def send_agg_weights(hosts, ports, fernets):
    print("========== Server sending agg weights ==========\n")
    for h, p, f in zip(hosts, ports, fernets):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((h, p))
        directory = '/home/014505660/fl_project/TensorFlow-2.x-YOLOv3/server_agg_weights'

        with s:
            sbuf = buffer.Buffer(s)
            sbuf.set_fernet(f)
            print(
                "========== Iniating connection for Client with host {} and port {} \n"
                .format(h, p))
            for file_name in os.listdir(directory):
                if "index" in file_name or "data" in file_name:
                    print('File Path', directory + '/' + file_name, '\n')
                    full_filename = directory + '/' + file_name
                    sbuf.put_utf8(file_name)
                    file_size = os.path.getsize(full_filename)
                    print('Send file: ', full_filename, ', size: ', file_size,
                          '\n')
                    sbuf.secure_send_file(full_filename)
                    print('File Sent successfully \n')

        s.close()
        print("Weights Files sent to Client successfully \n")
Esempio n. 8
0
 def __init__(self, fname, bufsize=64 * 1024 * 1024):
     self.fname = fname
     self.lastfno = 0
     self.lasttstamp = 0.
     self.fd = open(self.fname)
     self.buf = buffer.Buffer(None, size=bufsize)
     self.savedData = None
def rec_agg_weights(fernet):
    HOST = '0.0.0.0'
    PORT = 2005
    ThreadCount =0
    
    s = socket.socket()
    s.bind((HOST, PORT))
    s.listen(10)
    print("==================== Client is listening =================\n")

    def multi_client(connbuf):
        count = 0
        while True:
            file_name = connbuf.get_utf8()
            if not file_name:
                break
            clientname = '/home/014505660/fl_project/TensorFlow-2.x-YOLOv3/checkpoints'
            file_name = os.path.join(clientname, file_name)
            print('file name: ', file_name)
            file_size = int(connbuf.get_utf8())
            print('-------------Encrypted file size: ', file_size )

            connbuf.secure_recv_file(file_size, file_name)

    while True:
        conn, addr = s.accept()
        print("Got a connection from ", addr)
        connbuf = buffer.Buffer(conn)
        connbuf.set_fernet(fernet)
        multi_client(connbuf)
        print("Done receiving")
        conn.close()
        time.sleep(15)
        break
Esempio n. 10
0
def prepare(fn):
    b = buffer.Buffer()
    b.add_value("V1", 210)
    b.add_value("V1", 230)
    b.add_value("V1", 220)
    b.add_function('S_V1', fn, 'V1')
    b.process_function()
    return b
Esempio n. 11
0
 def readpack(self):
     """ Reads a single packet from the socket
        Used internally, must NOT be called from anywhere but read_thread lest bad things happen
        After reading the packet, if a handler is registered then we throw it to that handler in a greenlet
    """
     if self.protocol_mode < 3:
         max_bits = 21
     else:
         max_bits = 32
     packlen = self.recv_buff.unpack_varint(max_bits=max_bits)
     self.recv_buff.add(self.cipher.decrypt(self.tcp_sock.recv(packlen)))
     packbody = self.recv_buff.read(packlen)
     pack_buff = buffer.Buffer()
     pack_buff.add(packbody)
     if self.compression_enabled:
         uncompressed_len = pack_buff.unpack_varint()
         if uncompressed_len > 0:
             data = zlib.decompress(pack_buff.read())
             pack_buff = buffer.Buffer()
             pack_buff.add(data)
     try:
         ident = pack_buff.unpack_varint()
         k = (self.protocol_version, protocol_modes[self.protocol_mode],
              'downstream', ident)
         if packets.packet_names.has_key(k):
             if self.handlers.has_key(packets.packet_names[k]):
                 try:
                     if self.blocking_handlers:
                         self.handlers[packets.packet_names[k]](pack_buff)
                     else:
                         self.pool.spawn_n(
                             self.handler_wrapper, packets.packet_names[k],
                             self.handlers[packets.packet_names[k]],
                             pack_buff)
                 except:
                     yatelog.minor_exception(
                         'MCSock', 'Error scheduling packet handler')
             else:
                 yatelog.warn(
                     'MCSock', 'Received unhandled packet: %s' %
                     packets.packet_names[k])
         else:
             yatelog.error('MCSock', 'Unknown packet received: %s' % str(k))
     except:
         yatelog.minor_exception('MCSock',
                                 'Failed decoding received packet')
Esempio n. 12
0
 def make_box():
     return buffer.Buffer(width=self.width,
                          height=self.height,
                          data=[[[
                              int(r.triangular(0, 15)),
                              int(r.triangular(0, 7)),
                              chr(r.randint(0, 255))
                          ] for x in range(self.width)]
                                for y in range(self.height)])
Esempio n. 13
0
    def __init__(self, filename):
        self.__filename = filename
        self.__contents = buffer.Buffer(file(filename, "r").read())

        header = TarHeader(self.__contents)
        header.printInfo()
        self.__contents.setCurPos(512)
        header = TarHeader(self.__contents)
        header.printInfo()
Esempio n. 14
0
 def connect_to(self, endpoint):
     """ Use this to connect to the server if an endpoint is not passed in __init__
    """
     self.tcp_sock = eventlet.connect(endpoint)
     self.cipher = crypto.Cipher()
     self.recv_buff = buffer.Buffer()
     self.compression_enabled = False
     self.protocol_mode = 0  # did you really think it made sense to set this to anything else you maniac?
     self.send_q = eventlet.queue.LightQueue(0)
     self.ready = True
     self.pool.spawn_n(self.read_thread)
     self.pool.spawn_n(self.send_thread)
def clientthread(conn, addr):
    connbuf = buffer.Buffer(conn)
    # Sending message to connected client
    handshake_msg = '\nHello, ' + addr[0] + ':' + str(addr[1]) + '!\n'
    handshake_msg += 'Welcome to the server !!'
    connbuf.put_utf8(handshake_msg)  # send only takes string

    while True:
        time.sleep(0.2)  # wait for above message to send successfully
        # Receiving from client
        msg1 = '\nPress \'q\' or \'EXIT\' or \'exit\' to close the connection\n'
        msg1 += 'Enter username : '******'q' or temp == 'EXIT' or temp == 'exit':
            reply = '\nOkay...closing the connection from server side as requested by client\n'
            break
        else:
            reply = "\nOkay...username \'" + username + "\' received by main server successfully\n"
            print('Sending...', reply)
            connbuf.put_utf8(reply)

            time.sleep(0.2)
            msg2 = 'Now, Enter the password : '******'q' or temp == 'EXIT' or temp == 'exit':
                reply = '\nOkay...closing the connection from server side as requested by client\n'
                break

            temp = 0
            for server_number in range(1, 4):
                print('Checking server', server_number, '...')
                temp += handle_user(connbuf, username, password, server_number)
                if temp > 0:
                    break
            if temp == 0:
                reply = '\nOOPs...Either username or password is wrong, please try again !'
                connbuf.put_utf8(reply)

    connbuf.put_utf8(reply)
    conn.close()
    print('Connection with ',
          addr[0] + ':' + str(addr[1]) + ' client terminated successfully.')
Esempio n. 16
0
def main():
    """
        Test functions and properties of Buffers.

        The expected output is:
        Hello 5
        World
    """
    a = buffer.Buffer()
    a.bputs("Hello")
    print a.string, a.used
    a.string = "world"
    a.putb()
    def test_clear_plate_area(self):
        # Read from video, just one frame to test
        cap = cv2.VideoCapture("../../../test_plates/test_video_short.mp4")
        ret, frame = cap.read()
        self.assertTrue(ret)

        buff = buffer.Buffer()

        buff.frames.append(frame)

        processing.call_detect(buff)

        processing.clear_plate_area(buff)
        cv2.imwrite("test_picture.jpg", buff.frames[0])
    def test_call_detect(self):
        # Read from video, just one frame to test
        cap = cv2.VideoCapture("../../../test_plates/test_video_short.mp4")
        ret, frame = cap.read()
        self.assertTrue(ret)

        buff = buffer.Buffer()

        buff.frames.append(frame)

        processing.call_detect(buff)
        plate = buff.cars[0].plate

        self.assertTrue(plate)
Esempio n. 19
0
def writeCommand(command, *args):
    print "Write %s:" % command

    for arg in args:
        print "\t%20s : %s" % (type(arg), arg)

    print

    buf = buffer.Buffer()

    buf.writeEnum(OUT_COMMANDS, command)

    rpc2._write_list(buf, args)

    openttd.stdin.write(buf.getvalue())
Esempio n. 20
0
 def test_getch(self):
     x = 0
     y = 0
     for bgcolor in (colors.BLACK, colors.GREEN, colors.RED):
         for fgcolor in (colors.BLACK, colors.DARKGREY, colors.LIGHTGREY,
                         colors.WHITE, colors.RED, colors.LIGHTRED):
             x += 1
             y += 1
             p = buffer.Buffer(width=1,
                               height=1,
                               x=x,
                               y=y,
                               data=[[[fgcolor, bgcolor, 'Q']]])
             p.draw()
             term.flip()
             self.check(x=x, y=y, fg=fgcolor, bg=bgcolor, ch='Q')
Esempio n. 21
0
    def __init__(self, host='0.0.0.0', port=6666):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((host, port))
            s.listen(5)
        except socket.error as msg:
            print(msg)
            sys.exit(1)

        while True:
            conn, addr = s.accept()
            connbuf = buffer.Buffer(conn)
            recv_thread = threading.Thread(target=self.deal_data,
                                           args=(connbuf, addr))
            recv_thread.start()
Esempio n. 22
0
 def make_fall():
     color = random.choice([
         colors.WHITE, colors.LIGHTGREY, colors.LIGHTBLUE, colors.BLUE
     ])
     x = int(random.triangular(0, self.width, mode=center))
     return buffer.Buffer(width=1,
                          height=5,
                          x=x,
                          y=-4,
                          data=[
                              [[color, colors.BLACK, ' ']],
                              [[color, colors.BLACK, '\xb0']],
                              [[color, colors.BLACK, '\xb1']],
                              [[color, colors.BLACK, '\xb2']],
                              [[color, colors.BLACK, '\xdb']],
                          ])
Esempio n. 23
0
        def make_box(start_color):
            box = buffer.Buffer(width=self.width, height=self.height)
            i = 0
            bg = start_color
            fg = 0
            for x in range(self.width):
                for y in range(self.height):
                    fg += 1
                    if fg == 16:
                        fg = 0
                        bg += 1
                        if bg % 8 == 0:
                            bg = 0

                    box.set_at(x=x, y=y, char=chr(i % 256), bg=bg, fg=fg)
                    i += 1
            return box
Esempio n. 24
0
def drawGameMap():
    global MAPGENERATED, MAPUNCHANGED, BLOCKCOUPLER, BUFFERDRAWN, wholesurf, BUFFERLIST
    if MAPGENERATED == 0:  #Checks if map has been generated
        BUFFERDRAWN = 0
        wholesurf = pygame.Surface(
            (TILESIZE * TILEWIDTH, TILESIZE * TILEHEIGHT), pygame.SRCALPHA, 32)
        gametiles.initGenTile()
        bufferDisplayCreator(gametiles.BUFFERLIST)
        BUFFERDRAWN = 1
        [[
            displayTile(TILE, TILE.xpos, TILE.ypos, basetilesurf)
            for TILE in row
        ] for row in TILEMAP]  # Draw tiles
        MAPGENERATED = 1
    else:
        if len(drawStack.stackToDraw.stack) > 0:
            # print(drawStack.stackToDraw.stack)
            superNeighbourList = []
            tempDict = {}
            for item in drawStack.stackToDraw.stack:
                neighbourList = gametiles.getRowNeighbor(
                    item) + gametiles.getColumnNeighbor(item) + [item]
                print(neighbourList)
                for tiles in neighbourList:
                    tiles.setBlockID(100)
                    displayTile(tiles, item.xpos, item.ypos, basetilesurf)
                    tempBuffer = buffer.Buffer()
                    tempBuffer.setPos(tiles.xpos, tiles.ypos)
                    if (tiles.xpos, tiles.ypos) in tempDict.keys():
                        tempDict[(tiles.xpos, tiles.ypos)].append(tempBuffer)
                    else:
                        tempDict[(tiles.xpos, tiles.ypos)] = [tempBuffer]
                [superNeighbourList.append(x) for x in neighbourList]
                print(tempDict)
            listOfFreshBuffers = gametiles.grassWaterBuffer(
                tempDict, superNeighbourList)
            for x in listOfFreshBuffers.keys():
                buf = tempDict[x][0]
                gametiles.BUFFERLIST[(buf.x, buf.y)] = buf
            bufferDisplayCreator(listOfFreshBuffers)

            drawStack.stackToDraw.clearStack()
    DISPLAYSURF.blit(basetilesurf, (0, 0))
    DISPLAYSURF.blit(wholesurf, (0, 0))
Esempio n. 25
0
    def test_pattern(self):
        #inspired by the space-filler algorithm at https://dl.dropbox.com/u/1094010/Projs/spacefill.html
        #designed to use a lot of little buffers as an alternate performance test
        #it flips a new frame on every 25 calculations, to be a little fair to poor slow-flip winconsole
        r = random.Random()
        r.seed(1356317227)
        seen = set()
        candidates = [(r.randint(0, self.width), r.randint(0, self.height), 0)]
        step = 0
        buffers = []

        start = time.time()

        # just count the last one now
        draws = 1
        while candidates:
            next_index = step % len(candidates)
            x, y, depth = candidates.pop(next_index)
            step += 1
            for xoff, yoff in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
                nx = x + xoff
                ny = y + yoff
                if (
                        nx, ny
                ) in seen or nx < 0 or ny < 0 or nx > self.width or ny > self.height:
                    continue
                seen.add((nx, ny))
                candidates.append((nx, ny, depth + 1))

            b = buffer.Buffer(x=x,
                              y=y,
                              width=1,
                              height=1,
                              data=[[[step % 15 + 1, colors.BLACK, '\xb0']]])
            buffers.append(b)
            b.draw()
            if step % 25 == 0:
                term.flip()
                draws += 1

        term.flip()
        end = time.time()
        fps = draws / (end - start)
        log.debug("pattern FPS: %.2f over %r frames", fps, draws)
Esempio n. 26
0
    def __init__(self, platform, name):
        self.mPlatform = platform
        self.appNane = name

        strtime = time.strftime("_%Y_%m_%d_%H_%M_%S")
        self.dir = self.appNane + strtime
        os.mkdir(self.dir)

        self.mDevice = devices.Devices(self.mPlatform).get_device()
        self.mCon = connector.Connector('localhost', 8084)
        # self.eventsXML = xmls.EventsXML(self.mCon)
        # self.countersXML = xmls.CountersXML(self.mCon)
        self.capturedXML = xmls.CapturedXML(self.mCon)
        self.sessionXML = xmls.SessionXML(self.mCon)
        self.mAPC = apc.Apc(self.mCon, self.dir, '0000000000')
        self.mBuf = buffer.Buffer(self.mDevice, self.mCon, self.mAPC, self.capturedXML)
        self.mXls = xls.Xls(self.dir, 'Calc.xlsx', self.mDevice)
        self.status = -1

        for i in range(14):
            self.chkstatus.append(1)
Esempio n. 27
0
def main():
    global openttd, player_joined

    openttd = subprocess.Popen(
        args=[
            '/home/terom/my_ottd/openttd/trunk/bin/openttd', '-A', '-D',
            '0.0.0.0:8118'
        ],
        bufsize=0,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    print "OpenTTD running..."

    buf = ''

    while True:
        #        print "Reading with %d bytes in the buffer..." % len(buf)

        read = openttd.stdout.read(1)

        buf += read

        #        print "Read %d bytes for a total of %d bytes" % (len(read), len(buf))

        i = buffer.Buffer(buf)

        i.processWith(readCommand)

        buf = i.read()

        if player_joined:
            writeCommand("CMD_OUT_PLAYERS")
            player_joined = False
    def handle(self):
        # 定义连接变量
        conn = self.request
        print("client address:", self.client_address)
        connbuf = buffer.Buffer(conn)
        directory = {"directoryName": "", "files": {}}

        directoryName = connbuf.get_utf8()
        if not directoryName:
            conn.close()
            return
        directory.update({"directoryName": directoryName})
        print("directoryName ", directoryName)

        directoryHash = connbuf.get_utf8()
        if not directoryHash:
            conn.close()
            return
        directory.update({"directoryHash": directoryHash})
        print("directoryHash ", directoryHash)

        if redisTest.existDirInDb(directoryHash):
            connbuf.put_utf8("find")
            print("directory exist")
            conn.close()
            return
        else:
            connbuf.put_utf8("not find")

        while True:
            file_name = connbuf.get_utf8()
            if not file_name:
                break
            print("file_name ", file_name)

            originPath = connbuf.get_utf8()
            if not originPath:
                break
            print("originPath ", originPath)

            extensionName = file_name[file_name.rfind(".") + 1:]
            dirpath = os.path.abspath('./uploads') + "/" + extensionName
            print("extension name ", "." + extensionName)
            if not os.path.exists(dirpath):
                os.mkdir(dirpath)

            local_path = dirpath + '/' + \
                str(uuid.uuid1()) + '.' + extensionName
            fileDictionary = {'local_path': local_path}
            file_name = local_path
            print("local_path is ", local_path)

            file_size = int(connbuf.get_utf8())
            print('file size: ', file_size)

            hash_code = connbuf.get_utf8()
            if not hash_code:
                break
            print('hash code: ', hash_code)
            if redisTest.existInDb(hash_code):
                connbuf.put_utf8("find")
                local_path = redisTest.getFromDb(hash_code).get('local_path')
                print("file exists")
            else:
                connbuf.put_utf8("ok")
                redisTest.insertIntoDb(hash_code, fileDictionary)
                with open(local_path, 'wb') as f:
                    remaining = file_size
                    while remaining:
                        chunk_size = 4096 if remaining >= 4096 else remaining
                        chunk = connbuf.get_bytes(chunk_size)
                        if not chunk:
                            break
                        f.write(chunk)
                        remaining -= len(chunk)
                    if remaining:
                        print('File incomplete.  Missing', remaining, 'bytes.')
                    else:
                        print('File received successfully.')
            directory.get("files").update(
                {originPath: {
                    "filehash": hash_code,
                    "localPath": local_path
                }})

        redisTest.createDictory(directoryHash, directory)
        print('Connection closed.')
        conn.close()
def clientthread(conn, addr):
	connbuf = buffer.Buffer(conn)

	# Receiving from client
	data = connbuf.get_utf8()
	data = data.split(' ')

	reply = str(int(verify_user(data[0], data[1])))

	connbuf.put_utf8(reply)

	while reply == '1':
		meta_data = connbuf.get_utf8()
		meta_data = meta_data.split()
		print(meta_data)

		filename = 'received_' + meta_data[0]
		filesize = int(meta_data[1])
		buffer_size = int(meta_data[2])

		# To rewrite file
		temp_f = open(filename, "wb")
		temp_f.close()

		# start receiving the file from the socket
		# and writing to the file stream
		progress = tqdm.tqdm(range(filesize), f"Receiving {meta_data[0]}", unit="B", unit_scale=True, unit_divisor=1024)
		remaining = filesize
		while remaining > 0:
			chunk_size = buffer_size if remaining >= buffer_size else remaining+2
			chunk = connbuf.get_bytes(chunk_size)
			if not chunk: break
			
			#print('hello', remaining, chunk_size, chunk)

			#Checksum based error detection 
			chunk_t = chunk[1:len(chunk)-1]
			check_sum_byte = 0
			for byte in chunk_t:
				check_sum_byte = (check_sum_byte + byte)%256
				check_sum_byte = (check_sum_byte + 1)%256
			check_sum_byte = check_sum_byte + chunk[len(chunk)-1]

			try :
				x = chunk[:1]
				x = int(x.decode())
			except:
				x = 0

			if(check_sum_byte == 255):
				error_msg = 'No_Error'

				chunk = chunk[1:len(chunk)-1]
				f = open(filename, "ab")
				f.write(chunk)
				f.close()
				remaining -= len(chunk)

				#time.sleep(0.01)
				progress.update(len(chunk))
				
			else:
				error_msg = 'Error'

			connbuf.put_utf8(str((x+1)%2) + ' ' + error_msg)
			
		time.sleep(1)
		if remaining:
			final_msg = 'File incomplete.  Missing ' + remaining +' bytes.'
			print(final_msg)
		else:
			final_msg = 'From distributed server : File transmission done successfully.'
			print(final_msg)

		connbuf.put_utf8(final_msg)

		yes_no_msg = connbuf.get_utf8()
		if(yes_no_msg != 'y'):
			break


	# came out of loop
	conn.close()
	print('Connection with ', addr[0] + ':' + str(addr[1]) + ' client terminated successfully.')
Esempio n. 30
0
def my_server(show_1, HOST, PORT):

    BUFSIZE = 1024
    ADDR = (HOST, PORT)

    tcpTimeSrvrSock = socket.socket(AF_INET, SOCK_STREAM)
    tcpTimeSrvrSock.bind(ADDR)

    currentDT = datetime.datetime.now()
    e_file_1 = e_file.get()
    #e_key_v = str(e_key.get())

    #encryption start from here
    aes_key_generator()
    with open('key.key', 'rb') as f:
        data = f.read()
    key = data  # Can only use kdf once
    print(key)
    input_file = e_file_1
    output_file = 'file.encrypted'

    with open(input_file, 'rb') as f:
        data = f.read()

    fernet = Fernet(key)
    encrypted = fernet.encrypt(data)

    with open(output_file, 'wb') as f:
        f.write(encrypted)
        #send files to client
        sbuf = buffer.Buffer(tcpTimeSrvrSock)
        filename = output_file
        file = open(filename, 'rb')
        file_data = file.read(1024)
        tcpTimeSrvrSock.listen(5)
    while True:
        show_1.insert(END, "waiting for connection...")
        show_1.insert(END, "\n")
        #print ('waiting for connection...')

        tcpTimeClientSock, addr = tcpTimeSrvrSock.accept()

        #print ('...connected from:', addr)
        show_1.insert(END, "connected {}".format(addr))
        show_1.insert(END, "\n")
        #receive RSA public key from client
        with open('p_key.encrypted', 'wb') as f:
            public_key = tcpTimeClientSock.recv(1024)
            print(public_key)
            f.write(public_key)
            f.close()
            aes_decryption()
            rsa_encryption()
        #send files
        files = (output_file + 'key.encrypted')
        files_to_send = files.split()

        for file_name in files_to_send:
            print(file_name)
            sbuf.put_utf8(file_name)

            file_size = os.path.getsize(file_name)
            sbuf.put_utf8(str(file_size))

        with open(file_name, 'rb') as f:
            sbuf.put_bytes(f.read())
            print('File Sent')
            show_1.insert(END, "File Sent!")
            show_1.insert(END, "\n")