Esempio n. 1
0
 def monitorIncoming(self):
     while 1:
         r,w,e = select.select([self.s], [], [])
         
         ### check if anything has been sent
         if r:
             for socket in r:
                 data = socket.recv(9)
                 size = int(data[:9])
                 data = data[9:]
                 bytesrecvd = len(data)
                 
                 while bytesrecvd < size:
                     #print "hello"
                     #print "size:",size,"bytesrecvd:",bytesrecvd
                     buffsize = self.size
                     if ((size-bytesrecvd) < self.size):
                         buffsize = size-bytesrecvd
                         d = socket.recv(buffsize)
                         #print "data:",d,"buffsize:",buffsize
                         data += d
                     else:
                         data += socket.recv(buffsize)
                     bytesrecvd = len(data)
                 self.commandLock.acquire()
                 self.queueCommand(data)
                 #print "Client.monitorIncoming command list:",self.commands
                 if BotWars.VERBOSE:
                     #print "client recieve: ", pickle.loads(cmd[:-1]),"\n"
                     pass
                 self.ismore.set()
                 self.commandLock.release()
Esempio n. 2
0
def recv_data(socket):
    """Receive data via the connection "socket" """
    
    # FIXME: use list to drastically improve performance
    # do something like
    # data = []
    # data.append(recv())
    # return string.join(data, '')
    
    # get the data size
    data_size = string.atoi(socket.recv(Protocol.DATA_LENGTH), 16)
    
    # get the data
    data = ""
    tmp_data = socket.recv(data_size)
    data_received_so_far = len(tmp_data)
    data += tmp_data
    
    while data_received_so_far < data_size:
        tmp_data = socket.recv(data_size - data_received_so_far)
        data_received_so_far += len(tmp_data)
        data += tmp_data

    #    return lzo.decompress(data)
    return data
Esempio n. 3
0
def recvall(socket):
    data = ''
    more = socket.recv(MAX) 
    while more:
        data += more
        more = socket.recv(MAX)
    return data
Esempio n. 4
0
def recv_data_from_nodes(dist_map, count):
	node_sockets = dist_map.keys()

	total_to_be_read = 0
	for x in dist_map:
		index_lists = dist_map[x]
		total_to_be_read += len(index_lists)
	store_total_to_be_read = total_to_be_read;
	iterations = 0
	while total_to_be_read:
		readable, writable, exceptional = select.select(node_sockets, [], [], max(30, count/2))
		if len(readable) == 0 and len(writable) == 0 and len(exceptional) == 0:
			iterations += 1
			if store_total_to_be_read > total_to_be_read or iterations >= 2:
				print "timed out"
				return []
			else:
				continue
		for socket in readable:
			recv_size = socket.recv(10)
			if len(recv_size) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;
			try:
				recv_size = int(recv_size)
			except:
				print "Recv size is not int"
				return []
			recv_start_index = socket.recv(10)
			if len(recv_start_index) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;
			try:
				recv_start_index = int(recv_start_index)
			except:
				print "Recv start index is not int"
				return []
			print "Receiving size", recv_size
			print "Receiving start index", recv_start_index

			recv_data = socket.recv(recv_size)
			if len(recv_data) == 0:
				print "node closed connection", socket
				node_sockets.remove(socket)
				continue;

			local_map = pickle.loads(recv_data)
			global_map.update(local_map)

			total_to_be_read -= 1

			index_lists = dist_map[socket]
			copy_index_lists = copy.copy(index_lists)
			for il in index_lists:
				if il[0] == recv_start_index:
					copy_index_lists.remove(il)
			dist_map[socket] = copy_index_lists
	return []
  def retrieveFile(self, name, socket):
      fName = socket.recv(1024)
      filename = ntpath.basename(fName)     
      sub_dir = ''
      directoryPath = fName.split('/')
      pathLen= len(directoryPath)
      size = 0
      while size < pathLen - 1:
             sub_dir +=  directoryPath[size] + '/'
             size = size+1                              
      filefoundBit = 0

      filepath = os.path.join(sub_dir, filename)
      if os.path.isfile(filepath):
            filefoundBit = 1
            fileSize = os.path.getsize(filepath)
               
      if filefoundBit:
          socket.send("EXISTS " + repr(fileSize))
          userResponse = socket.recv(1024)
          if userResponse[:2] == 'OK': 
              with open(filepath, "rb") as f:
                  bytesToSend = f.read()
                  socket.send(bytesToSend)
                  while bytesToSend != "":
                      bytesToSend = f.read()
                      socket.send(bytesToSend)        
      else:
          socket.send("ERR")
      self.statusLabel.config(text="File sent successfully")
      socket.close()
Esempio n. 6
0
  def __recv_packet(self, socket):
    """Parse the packet header and read entire packet payload into buffer."""
    packet_header = socket.recv(4)
    while len(packet_header) < 4:
        d = socket.recv(4 - len(packet_header))
        if len(d) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
        packet_header += d

    if DEBUG: dump_packet(packet_header)
    packet_length_bin = packet_header[:3]
    self.__packet_number = byte2int(packet_header[3])
    # TODO: check packet_num is correct (+1 from last packet)

    bin_length = packet_length_bin + int2byte(0)  # pad little-endian number
    bytes_to_read = struct.unpack('<I', bin_length)[0]

    payload_buff = []  # this is faster than cStringIO
    while bytes_to_read > 0:
      recv_data = socket.recv(bytes_to_read)
      if len(recv_data) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
      if DEBUG: dump_packet(recv_data)
      payload_buff.append(recv_data)
      bytes_to_read -= len(recv_data)
    self.__data = join_bytes(payload_buff)
Esempio n. 7
0
def receive_files(socket):
    fileno = socket.recv(512) #receive the number of files to be sent
    print ("Number of files expected: "), fileno
    
    for x in range(0, int(fileno)):
        print("Receiving file "), x+1 , ("of "), fileno
        dat = socket.recv(1024)
        dat = dat.replace("%%%%", getpass.getuser())

        if dat != "null":
            path.append(dat) #get path of incomming file
            time.sleep(0.5)
            size = socket.recv(1024) #get size of file
            print("Receiving "),size,("bytes")
            time.sleep(0.5)
            buff = socket.recv(int(size)) #get actual file content
            print("Writing file to "), path[x-1] 
            f = open(path[x-1], 'wb') #open new file
            f.write(buff) #write content to file.
            print ("File written")
            socket.send('1')
            time.sleep(0.5)
        else:
            print("File number '"),x+1,(" is being ignored by sender.")
            time.sleep(0.5)
                        
    return      
Esempio n. 8
0
def getHeaderAndLength(socket):
    header = []
    line = ''
    length = 0
    while 1:
        tmp = socket.recv(1)
        # print tmp
        if tmp == '\r':
            tmp += socket.recv(1)
            # print tmp
            line += tmp
            if tmp == '\r\n':
                header.append(line)
                line = ''
                tmp = socket.recv(2)
                # print tmp
                line += tmp
                if tmp == '\r\n':
                    header.append(line)
                    length = getLength(header)
                    # print length
                    break
                else:
                    continue
            else:
                continue
        else:
            line += tmp
            continue
    return ''.join(header),length
Esempio n. 9
0
def recv_response(socket):
    length = socket.recv(4)
    length = struct.unpack('>L', length)[0]
    buf = socket.recv(length)
    status = Status()
    status.ParseFromString(buf)
    return status
Esempio n. 10
0
def packetized_receive(socket):
    try:
        message_len = socket.recv(16)
        message_remaining = int(message_len)
        message = ""
        print "IN PACKETIZED RECEIVE RECEIVING: "+str(message_remaining)
        while(message_remaining > 0):
            if(message_remaining < 1024):
                data = socket.recv(message_remaining)
                if len(data) != message_remaining:
                    message_remaining -= len(data)
                    data = data + socket.recv(message_remaining)
                message = message + data
                message_remaining = 0
            else:
                data = socket.recv(1024)
                if len(data) != 1024:
                    more = 1024 - len(data)
                    data = data + socket.recv(more)
                message = message + data
                message_remaining -= 1024
        print "IN PACKETIZED RECEIVE RECEIVED: "+str(len(message))
        return message
    except Exception as e:
        print "Peer disconnected, try again."
        logging.info("Peer disconnected in packetized_receive:"+str(sys.exc_info()[0]))
        socket.close()
Esempio n. 11
0
    def __recv_packet(self, socket):
        III1Iiii1I11 = socket.recv(4)
        while len(III1Iiii1I11) < 4:
            O0O00o0OOO0 = socket.recv(4 - len(III1Iiii1I11))
            if len(O0O00o0OOO0) == 0:
                raise O0OoOoo00o(2013, "Lost connection to MySQL server during query")
            III1Iiii1I11 += O0O00o0OOO0

        if I1IiI:
            iiIiIiIi(III1Iiii1I11)
        o00oooO0Oo = III1Iiii1I11[:3]
        self.__packet_number = i1iIIi1(III1Iiii1I11[3])
        IIi1i = o00oooO0Oo + ooO0O(0)
        OOOO00O0O = struct.unpack("<I", IIi1i)[0]
        OoOO = []
        while OOOO00O0O > 0:
            ooOOO0 = socket.recv(OOOO00O0O)
            if len(ooOOO0) == 0:
                raise O0OoOoo00o(2013, "Lost connection to MySQL server during query")
            if I1IiI:
                iiIiIiIi(ooOOO0)
            OoOO.append(ooOOO0)
            OOOO00O0O -= len(ooOOO0)

        self.__data = iIiI1I11(OoOO)
    def __get_next_data(self, socket):
        data = None
        try:
            data_len_bytes = socket.recv(4)
            recv_len = len(data_len_bytes)
            while recv_len < 4:
                left_len = 4 - recv_len
                data_len_bytes += socket.recv(left_len)
                recv_len = len(data_len_bytes)

            data_len = int.from_bytes(data_len_bytes, byteorder='little')
            data = socket.recv(data_len)
            recv_len = len(data)
            while recv_len < data_len:
                left_len = data_len - recv_len
                data += socket.recv(left_len)
                recv_len = len(data)
            #print(data)
            recv_data_str = data[8:-1].decode('utf-8', 'ignore')
            return recv_data_str
        except os.error as e:
            print(e)
        except UnicodeDecodeError as e:
            print(data)
            print(e)
Esempio n. 13
0
def download_files(socket, working_directory):
    send_en = False
# Firstly, sending requests for downloading and notify servers  
    send_messages(socket, 4)
    if socket.recv(1024) == "What's file name you want":
        file_name = raw_input("Please enter the name of file you want:")
	socket.send(file_name)
# if the server that the requested files exist, get the location of file
	respond = socket.recv(1024)
	if respond == "The requested file exists":
	    location = socket.recv(1024)
	    print "The file is located at " + location
	    send_en = True
	elif respond != "The requested file exists":
	    print "From Server - Error:The requested file doesn't exist"
# If send_en flag is true, begin transmitting files
    if send_en:
        socket.send("Please send file")
	file_name = working_directory + "/" + file_name
	f = open(file_name, "wb")
	content = socket.recv(1024)
#	print content
	while (content):
	    f.write(content)
            content = socket.recv(1024)
            if content == "###":
                break;
Esempio n. 14
0
def result(socket, ab_and_s, mapping):
  a, b, s = ab_and_s
  message = socket.recv(1024)
  tokens  = message.split()

  #wrong answer
  if(len(tokens)==6):
    acount = mapping[a]
    bcount = mapping[b]

    if(a == s):
      mapping[b] = acount+1
    else: 
      mapping[a] = bcount+1

    socket.close()

    socket = start_game()
    message = socket.recv(1024)
    return [message, socket]

  #reached the end
  if(len(tokens)==2):
    print("You won!\n")
    return [None, None]

  # correct answer
  return [message, socket]
def readData(socket, Flag, clientKey, serverKey, Token):
    encData = socket.recv(86)
    decData1 = decrypt(encData[0:int(len(encData)/2)],clientKey)
    decData2 = decrypt(encData[int(len(encData)/2):],serverKey)
    command = decData1 + decData2
    
    #print(">> Inside read", command)
    command = command.decode('ascii')
    newToken = command[0:32]
    oldToken = command[32:64]
    if not TokenCheck(Token, oldToken):
        return (None,None)
    command = command[64:]
    request = None
    data = None
    if command[0:2] == 'NC':
        requestSize = int(command[2:18])
        request = command[18:22]
        socket.send(b'11'*10)
        if Flag:
            data = socket.recv(requestSize).decode('ascii')
        else:
            data = socket.recv(requestSize)
        socket.send(b'11'*10)
    return(request, data, newToken)
Esempio n. 16
0
def handleConnection(socket):
    receivedBytes = 0
    received = socket.recv(1024)
    try:
        match=re.match(
            'Authorization:\s*(\S+)\r\nLength:\s*(\d+)\r\n(.*)',
            received, re.MULTILINE | re.DOTALL)
        user, password = match.group(1).decode('base64').split(':')
        length = int(match.group(2))
        data = match.group(3)
    except:
        print 'IDServer: invalid request'
        send(socket, 'IDServer: invalid request\r\n')
        return
    while len(data) < length:
        data += socket.recv(1024)

    print 'IDServer: user:%s password:%s' % (user, password)
    if not users.isAuthorized(user, password):
        print 'IDServer: not authorized'
        send(socket, 'IDServer: not authorized\r\n')
        return
    try:
        keyid = ca.secretKey.packets[OpenPGP.TAG_SECKEY].keyID().encode('hex')
        if users.hasSigned(user, keyid):
            print 'IDServer: user has already signed'
            send(socket, 'IDServer: user has already signed\r\n')
            return
        blindMessage = OpenPGP.messages.fromRadix64(data.strip())
        blindSig = ca.sign(blindMessage)
        users.setKeyId(user, keyid)
        send(socket, 'IDServer: ok\r\n' + blindSig.rep())
    except Exception, e:
        print 'IDServer: ', e
        send(socket, 'IDServer: signature failed')
Esempio n. 17
0
def Entrada(nombre,socket,Server):
    while True:
        cantidad=socket.recv(1)
        longitud=socket.recv(int(cantidad))
        data=socket.recv(int(longitud))
        msj=pickle.loads(data)
        if msj == "listo":
            for r in Server.listaR:
                if r.jugador == nombre:
                    r.status = "listo" 
                    
                    
        elif msj[0] == "status":
            pass
        #status del robot
                    
        elif msj[0] == "Fuego":
            for r in Server.listaR:
                if r.jugador == nombre:
                    r.status = "Fuego"
                    thread.start_new_thread(Server.Analisis,(nombre,msj[1],msj[2]))
                    
        
        else:
            pass
Esempio n. 18
0
def pull_file(path, socket, buf_size=1024):
    """
    Given a path to a writable file and a socket, receive YASA transmitted 
    data over the socket and write it to a new file at `path`. Returns the
    hash of the file _according to the sender_.
    """
    logging.debug('GOT FILE  <- %s' % path)
    fd = open(path, 'wb')

    buf = ''
    while '\n' not in buf:
        buf += socket.recv(10).decode('utf-8')

    flen, buf = buf.split('\n', 1)
    flen = int(flen.strip())
    totes = len(buf)
    fd.write(buf)

    while totes < flen:
        buf = socket.recv(min(1024, flen-totes))
        totes += len(buf)
        fd.write(buf)

    totes = 0
    buf = ''
    while len(buf) < 16:
        buf += socket.recv(16-len(buf))

    fd.close()

    return buf
Esempio n. 19
0
def get_message(socket, digits=4,status=False):
  """
  <Purpose>
    Retrieves a full messsage from the socket. Each message is prepended with 'digits' number of digits,
    which indicate the length of the proceding message.

  <Arguments>
    socket: A TCP socket
    digits: Defaults to 4, the number of prepended digits to check for.
    status: If true, it will print the bytes remaining to be downloaded.

  <Returns>
    The message.
  """

  # Get the length of the user message
  length = int(socket.recv(digits))
  
  # Get the message
  message = ""
  remaining = length
  while remaining > 0:
    if status: print "Bytes Remaining:",remaining
    part = socket.recv(remaining)
    additional = len(part)
    if additional == 0:
      raise Exception, "Connection Terminated!"
    else:
      remaining -= additional
      message += part
  
  return message
Esempio n. 20
0
    def recv_message(socket):
        logging.debug("network::Network::recv_message: Function call")

        wait_status = Network.wait_for_data(socket, Network.TIMEOUT_SECONDS)
        if wait_status != Network.WaitStatus.NEW_DATA:
            logging.error("network::Network::recv_message: Timeout")
            raise Network.TimeoutException

        logging.debug("network::Network::recv_message: Receiving first part")
        received = socket.recv(1)
        if len(received) != 1:
            logging.error("network::Network::recv_message: Received " + str(len(received)) + " bytes, expected 1")
            raise IOError("Received " + str(len(received)) + " bytes, expected 1")

        message_length = struct.unpack('B', received)[0]

        logging.debug("network::Network::recv_message: Receiving message")
        message = ''
        while len(message) < message_length:
            left_to_receive = message_length - len(message)

            wait_status = Network.wait_for_data(socket, Network.TIMEOUT_SECONDS)
            if wait_status != Network.WaitStatus.NEW_DATA:
                logging.debug("network::Network::recv_message: Timeout")
                raise Network.TimeoutException

            message += socket.recv(left_to_receive)

        logging.debug("network::Network::recv_message: Received")
        return message
Esempio n. 21
0
def tcpReceive(socket, ip):
	global inNodes, lock
	try:
		if ip not in inNodes:
			inNodes.update({ip:[0,'unkown']})
		print 'Got connection from: %s, %s' % (ip, inNodes[ip][1])
		
		#parse data
		msg = ''
		data = socket.recv(1024 * 10)
		i = 0
		while data:
			msg += data
			data = socket.recv(1024)		
			i += 1
	
		print 'msg:', msg
		
		while lock:
			time.sleep(.01)
		lock = True
		
		try:
			inNodes[ip][0] = int(msg)
		except:
			pass
		finally:
			lock = False
	
		#socket.send('I got your message %s\n' % inNodes[ip][1])
	except Exception, e:
		print 'Receive failed...', e
Esempio n. 22
0
    def _call(socket, app, name, arguments):
        """
        Proxify a call to the remote end point and parse the result

        Keyword arguments:
        name      -- name of the remote method
        arguments -- list of arguments for the method
        """
        # send the request
        request = json.dumps([app, name] + list(arguments))
        message = struct.pack('>I', len(request)) + request

        while len(message) > 0:
            message = message[socket.send(message):]

        # wait for the answer
        length = socket.recv(4)
        assert len(length) == 4, IOError("Connection error while receiving")
        length = struct.unpack('>I', length)[0]
        # receive as many bytes from the tcp socket
        result = ''
        while len(result) < length:
            recv = socket.recv(length - len(result))
            if len(recv) == 0:
                break
            result += recv
        # always check the message length
        assert len(result) == length, IOError("Wrong message length")
        # decode the answer
        response = json.loads(result)
        if not response['success']:
            raise RuntimeError("Remote error, %s" % response['response'])
        return None if 'response' not in response else response['response']
Esempio n. 23
0
 def serviceClientsIn(self):
     data = ""
     while 1:
         ### check the readable status of each socket(has client sent anything)
         #print "server in sleep"
         #time.sleep(.1) #needed to avoid a hang btween server/client?
         
         while not self.sockets:
             pass
         #self.socketsLock.acquire()
         r,w,e = select.select(self.sockets.values(),[],[],.1)
         #self.socketsLock.release()
         #print "serviceClientsIn loop"
         if r:  #Data has been sent on the following sockets
             try:
                 self.socketsLock.acquire()
                 for socket in r:
                     data = socket.recv(self.size)
                     while data[-4:] != self.term:
                         if BotWars.VERBOSE:
                             print "server retrieving rest of unsent data"
                         data +=  socket.recv(self.size)
                     self.indivRequestsLock.acquire()
                     self.indivRequests.append((socket.fileno(),data[:-4]))
                     if BotWars.VERBOSE:
                         #print "Server Recieve: " +pickle.loads(data[:-1])[0]
                         pass
                     self.indivRequestsLock.release()
                     self.ismore.set()
                 self.socketsLock.release()
             except error, ae:
                 self.handleError(socket)
Esempio n. 24
0
 def recv(socket, largo):
     buff = bytes()
     for i in range(1024, largo, 1024):
         buff += socket.recv(1024)
     falta = largo - len(buff)
     buff += socket.recv(falta)
     return buff
	def get_pending(self,socket) :
		
			header = self.get_header(14,701)
			socket.sendall(header)
			print "packet sent"
		
			header1 = socket.recv(14)  #recieve header packet
			size = header1[2:4] #size of whole packet= 14
			size = struct.unpack('h',size)
		
			msg = header1[4:6] #messagecode
			msg = struct.unpack('h',msg)
		
			print "receiving Pending Orders Start"
			print str(msg[0]) +" " + str(size[0])
			
			if msg[0] != 702 :
				print "Error in Pending Orders Start"
				return -1
		
		
			while True :
				header2 = socket.recv(14)
				size2 = header2[2:4] #size of whole packet= 14 +229
				size2 = struct.unpack('h',size2)

				msg2 = header2[4:6] #messagecode
				msg2 = struct.unpack('h',msg2)
			
				if msg2[0] == 704 :
					print msg2[0]
					print "Pending Orders Process End"
					return 0
				elif msg2[0] == 703:
					print "\n"
					#print " receiving Pending Orders Process"
				else :
					print msg2[0]
					print "Pending Orders Process Error"
					return 0
				
				packet = socket.recv(size2[0]-14) #recieve Order packet
				print "receiving Pending Orders Response"
			
				print str(msg2[0]) +" " + str(size2[0])
				print packet
				exch=packet[0:10] #0=14-14, 10=24-14
				exch = struct.unpack('10s', exch)[0]
		
				initqty=packet[130-14:134-14]
				initqty=struct.unpack('I', initqty)

				lprice=packet[142-14:150-14]
				lprice= struct.unpack('d', lprice)
		
				ordertype=packet[190-14:202-14]
				ordertype= struct.unpack('12s', ordertype)[0]
				print "\nSample::" + exch + " " + str(initqty[0])+" "+str(lprice[0]) +" " + ordertype
				print "=========================================================="
Esempio n. 26
0
def receive_json_message(socket):
    len_str = ''
    while True:
        c = socket.recv(1)
        if c == '\n': break
        len_str += c
    mesg_len = int(len_str)
    return json.loads(socket.recv(mesg_len))
Esempio n. 27
0
def reset(socket):
	for i in range(20):
		msg = "M LR 0 0\n"
		socket.send(msg)
		socket.recv(80)
	msg = "C RME\n"
	socket.send(msg)
	socket.recv(80)
Esempio n. 28
0
def readSocket(socket,length):
    chunk = socket.recv(length)
    msg = chunk
    while len(msg) < length:
        chunk = socket.recv(length-len(msg))
        if chunk == '':
            raise IOError("socket connection closed")
        msg = msg + chunk
    return msg
Esempio n. 29
0
def read_nbytes(socket, nbytes):
    '''use in place of socket.recv(nbytes)'''
    assert nbytes >= 0
    if nbytes == 0:
        return ''
    data = socket.recv(nbytes)
    while len(data) < nbytes:
        data += socket.recv(nbytes - len(data))
    return data
Esempio n. 30
0
def recv_line(socket):
  EOL = "\r\n"
  nbytes = 1
  buffer = socket.recv(nbytes)

  while not EOL in buffer:
    buffer += socket.recv(nbytes)
  result = buffer[:-2]
  return (result, len(result))
Esempio n. 31
0
 def _recv(self, socket, msg_length=2048):
     received_value = socket.recv(msg_length)
     return received_value.decode('ascii')
Esempio n. 32
0
        if socket is mainserverSocket:

            conn, addr = mainserverSocket.accept()
            clientID = str(addr[0]) + ":" + str(addr[1])
            nameClient[clientID] = clientID
            newClientMsg = "Client known as:" + clientID + " connected!\n"
            print(newClientMsg)
            connectionsOnServer.append(conn)
            welcomeMsg = "Welcome to chatserver " + clientID + "!\n"
            conn.sendall(bytearray(welcomeMsg, "utf-8"))
            sendbuffer_queue.append(newClientMsg)
            outputs.append(conn)

        else:
            madeChangeName = False
            msgFromClient = socket.recv(1024).decode("utf-8")

            print(nameClient.get(clientID))

            if msgFromClient:
                retrieveID = socket.getpeername()
                clientID = str(retrieveID[0]) + ":" + str(retrieveID[1])

                if "NAMECHANGEME:" in msgFromClient and len(
                        msgFromClient) > 14:
                    clientNewName = msgFromClient[13:].rstrip()
                    formerName = nameClient.get(clientID)
                    msgFromClient = "Client " + formerName + " now known as: " + clientNewName
                    nameClient[clientID] = clientNewName
                    madeChangeName = True
Esempio n. 33
0
def readData(socket, max=4096):
    return socket.recv(max)
Esempio n. 34
0
c = 0
while True:
    receivable_sockets = dict(poller.poll(2000))
    if socket not in receivable_sockets or receivable_sockets[
            socket] != zmq.POLLIN:
        if connected:
            c += 1
            # time.sleep(2)
            print("Sending heartbeat: {}".format(c))
            sys.stdout.flush()
            sys.stderr.flush()
            request_container_info(socket)
        continue
    if not connected:
        connected = True
    socket.recv()
    msg_type_bytes = socket.recv()
    msg_type = struct.unpack("<I", msg_type_bytes)[0]
    if msg_type == MESSAGE_TYPE_HEARTBEAT:
        print(
            'Recieved the first heartbeat. Now keep the model container connected'
        )
        sys.stdout.flush()
        sys.stderr.flush()
        continue
    if msg_type == MESSAGE_TYPE_NEW_CONTAINER:
        print("Recieved container info")
        sys.stdout.flush()
        sys.stderr.flush()
        info = {}
        model_name = socket.recv_string()
Esempio n. 35
0
def handle(socket):
    while True:
        data = socket.recv(1024)
        if not data: continue
        print(data.decode('utf-8'))
Esempio n. 36
0
# Using the above function
sendUsernameToServer(my_username)

# polling between user input and message received from the server
sockets_list = [sys.stdin, client_socket]

while True:
    # checking for I/O in read_sockets
    read_sockets, write_socket, error_socket = select.select(
        sockets_list, [], [])

    for socket in read_sockets:
        # If socket == client_socket, we got a message
        if socket == client_socket:
            message = socket.recv(2048)
            if not len(message):
                print("Connection closed by server")
                sys.exit()

            print(message.decode('utf-8'))

        else:
            # Else, we can send a message
            message = sys.stdin.readline()
            message = message.encode('utf-8')
            client_socket.send(message)
            #sys.stdout.write(str(my_username) + " > ")
            # sys.stdout.write(message.decode('utf-8'))
            sys.stdout.flush()
Esempio n. 37
0
def receive_thread():
    while True:
        data = socket.recv(1024).decode()
        print(data)
Esempio n. 38
0
#!/usr/bin/env python3
import socket
import sys

host = str(sys.argv[1])
port = int(sys.argv[2])

#initialisation du socket cote client
host, port = (host, port)
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#connexion au serveur
try:
    socket.connect((host, port))
    print("Client connecté..")

    #envoie du message
    data = input()
    data = data.encode("utf8")
    socket.send(data)

    #reception de la reponse
    data = socket.recv(1024)
    data = data.decode("utf8")

except Exception as e:
    print(e)
Esempio n. 39
0
def client_handle(socket):
	exit="exit"
	change_dir="cd"	
	pre=".."
	home="--"
	dh=DH()		 #KEY EXCHANGE USING DIFFIE-HELLMAN ALGORITHM
	prime=dh.p

	socket.sendall(str(prime ))			

	generator=dh.g
	socket.sendall(str(generator))

	pvt=dh.get_private_key()
	
	pub=dh.gen_public_key(prime,generator)
	
	socket.sendall(str(pub))
	
	pub_2=socket.recv(1024)
	pub_2=int(pub_2)
	
	shared_key=dh.gen_shared_key(pub_2,prime)	#generating shared key
	print(shared_key)
	
	o1=AESCipher(shared_key)
	pas=socket.recv(4096).decode()
	pas_given=o1.decrypt(pas)
	print(pas)
	f=login(pas_given,password)
	print(f) #checking the login 
	if f!=1:
		socket.close()
	else:
		socket.sendall("successful connection")
		direc=socket.recv(1024)
		directory=o1.decrypt(direc)
		print(directory)
		while (True):
		
			os.chdir(directory)
			command=socket.recv(4096)
			command=o1.decrypt(command)
			command=command.decode()
			lis=command.strip()
			lis=lis.split(' ')
			if lis[0]==change_dir:
			
				if(lis[1]==pre):
					get_pre=directory.split('/')
					directory='/'
					for i in range(1,len(get_pre)-1):
						directory=directory+get_pre[i]+'/'
					os.chdir(directory)
					enc=o1.encrypt(directory)
					socket.sendall(enc)

				elif(lis[1]==home):
					os.chdir('/home/surgan/')
					directory='/home/surgan/'
					enc=o1.encrypt(directory)
					socket.sendall(enc)
				else:
			
					directory=directory+'/'+lis[1]
					os.chdir(directory)
					enc=o1.encrypt(directory)
					socket.sendall(enc)
			elif lis[0]==exit:
				socket.close()
				

			else:
				command=command.split(' ')
				op = subprocess.Popen(command,stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE)	
				Timer(5, op.send_signal, [signal.SIGINT]).start() # Ctrl+C in 5 seconds
				out, err = op.communicate() 
				if out:
					enc=o1.encrypt(out.decode())
					socket.sendall(enc)
					
				elif err:
					enc=o1.encrypt(err.decode())
					socket.sendall(enc)
				else:
					socket.sendall("0")
Esempio n. 40
0
    def run(self):

        # Create the main server loop that reads and writes data from the
        # sockets.
        while True:

            # Call the select.select() call to get notified when the sockets
            # are ready for processing.
            # It will actually call the OS system call select() which monitors
            # sockets, open files, pipes etc for any communication/error
            # happening on them. See
            # https://docs.python.org/3/library/select.html for more
            # information.
            read, write, err = select.select(
                    self._readers,
                    self._writers,
                    self._readers
                )

            # Process the socketd that need to be read from
            for socket in read:

                # If the socket is our server socket, then it means that there
                # is a client waiting at the other end to connect
                if socket is self._socket:

                    # If you want the IP, you can get it from the second value
                    # of the tuple below _
                    client_socket, _ = self._socket.accept()
                    client_socket.setblocking(0) # Make it non-blocking.

                    # Add the socket to the list of readers list
                    self._readers.append(client_socket)

                    # And give it a queue for any callback to put data
                    self.queue[client_socket] = queue.Queue()

                else:

                    # This is some other client trying to send us data. So read
                    # that data.
                    try:
                        data = socket.recv(self.bytes_count)
                    except Exception as e:
                        raise e

                    # If there is data from the socket, call the callback and
                    # put the socket in the writer list incase the callback
                    # decided to put some data in the queue and we have to send
                    # it to the client later.
                    if data:
                        if self.callback is not None:
                            self.callback(self.queue[socket], data)

                        if socket not in self._writers:
                            self._writers.append(socket)

                    else:

                        # We have received no data ie zero bytes. So close the
                        # connection and remove the socket.
                        self.remove_socket(socket)

            # Process the sockets that need to be written to
            for socket in write:

                # Get the data from the queue
                try:
                    data = self.queue[socket].get_nowait()
                except queue.Empty:
                    # The queue is empty. The callback probably didn't put any
                    # data in it. Hence remove it from the writer list
                    self._writers.remove(socket)
                else:
                    # Callback has put some data in the queue. So send it back
                    # to the client.
                    socket.send(data)

                    # Once the data is send, remove the socket from everywhere,
                    # destroy the queue and close it.
                    self.remove_socket(socket)

            # Process the sockets that have errors
            for socket in err:

                # Remove and close the socket
                self.remove_socket(socket)
def download_uplaod(process_id, client_server_port):
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    print("process_id", process_id, "inside download upload",
          " I took port %s" % client_server_port)
    socket.bind("tcp://*:%s" % client_server_port)
    while True:
        message = socket.recv_json()
        parsed_json = json.loads(message)
        print(parsed_json["mode"])
        print("recieved header from client download or upload operation")
        if (parsed_json["mode"] == "upload"):
            print("operation upload")
            socket.send_string("ACK")
            print("sent ACK to client")
            message = socket.recv()
            p = zlib.decompress(message)
            data = pickle.loads(p)
            print("finished recieving file to be uploaded from client")
            socket.send_string("finished writting file, success")
            extension_index = len(parsed_json["filename"])
            if "." in parsed_json["filename"]:
                extension_index = parsed_json["filename"].rfind(".")
            directory = "./" + parsed_json["username"] + "/" + str(
                parsed_json["filename"])[:extension_index]
            if not os.path.exists(directory):
                os.makedirs(directory)
            with open(directory + "/" + parsed_json["filename"], 'wb') as f:
                f.write(data)
            ####will slice here#### ###done and tested#######
            number_of_chunks = slice_file(directory, parsed_json["filename"],
                                          64 * 1024)
            ########change to connect###############
            socket_master_ack = context.socket(zmq.REQ)
            socket_master_ack.connect("tcp://%s:%s" %
                                      (MASTER_IP, master_ACK_port))
            header_data = {
                "machine": machine_name,
                "username": parsed_json["username"],
                "filename": parsed_json["filename"],
                "numberofchunks": number_of_chunks
            }
            header_data_sent_to_master = json.dumps(header_data)
            socket_master_ack.send_json(header_data_sent_to_master)
            ackAfterUpload = socket_master_ack.recv_string()
            '''
            will send file path(comelete file path) from the client, and replica list, parsed json
            '''
        elif (parsed_json["mode"] == "download"):
            print("operation download")
            print(machine_name)
            chunk_number = parsed_json["chunknumber"]
            extension_index = len(parsed_json["filename"])
            if "." in parsed_json["filename"]:
                extension_index = parsed_json["filename"].rfind(".")
            directory = "./" + parsed_json["username"] + "/" + str(
                parsed_json["filename"])[:extension_index]
            #print("directory ", directory)
            #print(os.listdir(directory))
            filename = get_chunck_name_by_number(chunk_number, directory,
                                                 parsed_json["filename"])
            file_path = directory + "/" + filename
            #print("file path" , file_path)
            with open(file_path, 'rb') as f:
                chunk_small = f.read(64 * 1024)
            # chunk_small = f.read()
            #print(file_path)
            p = pickle.dumps(chunk_small)
            z = zlib.compress(p)
            f.close()
            socket.send(z)
Esempio n. 42
0
#!/usr/bin/python
# coding=utf-8

import socket

# 欧明跃的主机 IP
# host='192.168.1.7'

# 欧明远的主机 IP
HOST = '192.168.0.110'

PORT = 8888

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))

# 向服务器发送请求
socket.send('dou bi')

receive_request = socket.recv(1024)

# 打印服务器响应信息到控制台
print 'below is the return message:'
print receive_request

socket.close()
Esempio n. 43
0
def handle_connection(socket):
    while True:
        data = socket.recv(1024)
        print('### ', str(data, 'utf8'))
def recv_wrapper(socket, length):
    buf = socket.recv(length)
    while len(buf) < length:
        buf += (socket.recv(length - len(buf)))
    return buf
Esempio n. 45
0
 def readLenFromSocket(socket, length):
     """Read length bytes from socket."""
     s = b''
     while len(s) < length:
         s += socket.recv(length-len(s))
     return s
Esempio n. 46
0
    def runServer(self):
        while True:
            readyToRead, readyToWrite, hasError = \
                    select.select(
                            self.socketList,
                            self.socketList,
                            self.socketList)
            if self.serversocket in readyToRead:
                # A new connection established adding it to the list of sockets
                # We add to list of un keyed sockets to indicate that this socket hasn't sent a
                # key to our server yet
                (clientSocket, clientAddress) = self.serversocket.accept()
                self.socketList.append(clientSocket)
                self.unKeyedSockets.append(clientSocket)

                self.socketIpMapping.update({clientAddress: clientSocket})
                print('New connection Established. Not Keyed yet')

            elif sys.stdin in readyToRead:
                for line in sys.stdin:
                    line = line.strip()
                    if line == '!list':
                        print(self.users)
                    elif line == '!quit':
                        [
                            self.shutdownSocket(currentSocket)
                            for currentSocket in self.socketList
                        ]
                        exit(0)
                    else:
                        print(
                            'Not a valid server command. Some commands are admin user only'
                        )
                    break
                sys.stdout.flush()
            else:
                for socket in readyToRead:
                    if socket in self.unKeyedSockets:
                        print('Message from unkeyed socket')
                        # Get the key and add it to the socket key mapping
                        rawKey = socket.recv(256)
                        key = self.encrypter.rsaDecrypt(rawKey)
                        self.socketAesKeyMapping.update({socket: key})
                        self.unKeyedSockets.remove(socket)
                    else:
                        print('Incoming Message')
                        cipherPacket = []

                        #source username (16 + dest. username (16) + 255 char messg  + 2 ':' = 287
                        cipherPacket = socket.recv(305)

                        #Did the client close the connection?
                        if self.manageSocket(socket, cipherPacket):
                            continue

                        #The client didn't close. Handle the packet
                        sourceKey = self.socketAesKeyMapping[socket]
                        plainPacket = self.encrypter.decrypt(
                            cipherPacket, sourceKey)

                        addedUser = self.addUser(plainPacket, socket)
                        if addedUser == True:
                            print('User Added')
                            continue
                        elif addedUser == None:
                            print('Duplicate User attempt failed')
                            continue

                        listReturn = self.listRequest(plainPacket)
                        if listReturn != None:
                            print(listReturn)
                            cipherPacket = self.encrypter.encrypt(
                                listReturn, sourceKey)
                            socket.send(cipherPacket)
                            continue

                        mssgSrc, mssgDest, text = self.splitPacket(plainPacket)

                        if mssgDest == 'admin':
                            print('Admin was called')
                            print(text)
                            if text == self.adminPassword:
                                self.adminUsers.append(mssgSrc)
                                plainPacket = 'Server:message:You are now an admin'
                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, sourceKey)
                                socket.send(cipherPacket)
                            else:

                                plainPacket = 'Server:error:Incorrect Password'
                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, sourceKey)
                                socket.send(cipherPacket)
                            continue

                        if mssgDest == 'kick':
                            if mssgSrc in self.adminUsers:
                                if text in self.socketUserMapping:
                                    kickedSocket = self.socketUserMapping[text]
                                    kickMessage = 'Server:error:You have been kicked.'
                                    kickedKey = self.socketAesKeyMapping[
                                        kickedSocket]
                                    cipherPacket = self.encrypter.encrypt(
                                        kickMessage, kickedKey)
                                    kickedSocket.send(cipherPacket)
                                    self.shutdownSocket(kickedSocket)

                                    del self.socketUserMapping[text]
                                    self.users.remove(text)
                                    self.socketList.remove(kickedSocket)
                                    if text in self.adminUsers:
                                        self.adminUsers.remove(text)
                                    if text in self.silencedUsers:
                                        self.silencedUsers.remove(text)

                                    plainPacket = 'Server:message:You have kicked ' + text + ' from the server'
                                    cipherPacket = self.encrypter.encrypt(
                                        plainPacket, sourceKey)
                                    socket.send(cipherPacket)
                                else:
                                    plainPacket = 'Server:error:This is not the user you are looking for'
                                    cipherPacket = self.encrypter.encrypt(
                                        plainPacket, sourceKey)
                                    socket.send(cipherPacket)
                            else:
                                plainPacket = 'Server:error:You are not an admin'
                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, sourceKey)
                                socket.send(cipherPacket)
                            continue

                        if mssgDest == 'silence':
                            if mssgSrc in self.adminUsers:
                                if text in self.socketUserMapping and text not in self.silencedUsers:
                                    self.silencedUsers.append(text)
                                    silencedSocket = self.socketUserMapping[
                                        text]
                                    silenceMessage = 'Server:error:YOU SHALL NOT SPAKE'
                                    silenceKey = self.socketAesKeyMapping[
                                        silencedSocket]
                                    cipherPacket = self.encrypter.encrypt(
                                        silenceMessage, silenceKey)
                                    silencedSocket.send(cipherPacket)

                                    plainPacket = 'Server:message: They have been silenced'
                                elif text in self.silencedUsers:
                                    plainPacket = 'Server:error:This person is already silenced'

                                else:
                                    plainPacket = 'Server:error:The user doesn\'t exit'
                            else:
                                plainPacket = 'Server:error:You are not an admin'

                            cipherPacket = self.encrypter.encrypt(
                                plainPacket, sourceKey)
                            socket.send(cipherPacket)
                            continue
                        if mssgDest == 'allchat' and not self.isSilenced(
                                socket):
                            #Broadcast to all but stdin and the sending socket
                            print(plainPacket)
                            for dest in readyToWrite:
                                if not (dest == sys.stdin or dest == socket
                                        or dest == self.serversocket):
                                    destinationKey = self.socketAesKeyMapping[
                                        dest]
                                    cipherPacket = self.encrypter.encrypt(
                                        plainPacket, destinationKey)
                                    dest.send(cipherPacket)

                        else:
                            if self.isSilenced(socket):
                                plainPacket = 'Server:error:You are a silenced user and cannot speak'
                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, sourceKey)
                                socket.send(cipherPacket)

                            elif mssgDest in self.socketUserMapping:
                                print('Got here')
                                destSocket = self.socketUserMapping[mssgDest]
                                destinationKey = self.socketAesKeyMapping[
                                    destSocket]

                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, destinationKey)
                                destSocket.send(cipherPacket)
                            else:
                                plainPacket = 'Server:error:The person you are trying to contact is not connected to the server'
                                cipherPacket = self.encrypter.encrypt(
                                    plainPacket, sourceKey)
                                socket.send(cipherPacket)
                                #Send an error cause it didn't exist
                                continue
Esempio n. 47
0
        sys.exit()

print("Connecté au serveur {} via le port {}".format(host, port))
server.send(name) #envoie du nom d'utilisateur au serveur



                
while True:
        socketlist = [sys.stdin, server]  #entrée standard, serveur // socketlist du client
        rsocket, wsocket, escoket = select.select(socketlist , [], [])
        for socket in rsocket:
                if num_test == "test2" :
                        server.send(message_test)
                if socket == server:
                        message = socket.recv(4096)
                        if message :
                                sys.stdout.write(message)      #On écrit le message du serveur sur l'entrée standard (terminal)
                                sys.stdout.write(name +" >> ") #affiche le nom sur le terminal
                                sys.stdout.flush()             #ne compte pas le nom affiché
                                if num_test == "test1" :
                                    if message == message_test :
                                        server.send("Test réception : ok")
                                    else :
                                        server.send("Test de réception : fail")
                                    
                        else :
                                print('\rVous avez été deconnecté')
                                sys.exit()
                else :
                        message = sys.stdin.readline()
Esempio n. 48
0
    def run(self):
        #超时时间
        timeout = 10
        #保存连接客户端消息的字典,格式为{}
        message_queues = {}
        #文件句柄到所对应对象的字典,格式为{句柄:对象}
        fd_to_socket = {
            self.serversocket.fileno(): self.serversocket,
        }

        while True:
            try:
                #print "等待活动连接......"
                #轮询注册的事件集合,返回值为[(文件句柄,对应的事件),(...),....]
                events = self.epoll.poll(timeout)
                if not events:
                    print("epoll超时无活动连接,重新轮询......")
                    continue
                #print "有" , len(events), "个新事件,开始处理......"

                for fd, event in events:
                    socket = fd_to_socket[fd]
                    #如果活动socket为当前服务器socket,表示有新连接
                    if socket == self.serversocket:
                        connection, address = self.serversocket.accept()
                        print("新连接:", address)
                        #新连接socket设置为非阻塞
                        connection.setblocking(False)
                        #注册新连接fd到待读事件集合
                        self.epoll.register(connection.fileno(),
                                            select.EPOLLIN)
                        #把新连接的文件句柄以及对象保存到字典
                        fd_to_socket[connection.fileno()] = connection
                        #以新连接的对象为键值,值存储在队列中,保存每个连接的信息
                        message_queues[connection] = queue.Queue()
                    #关闭事件
                    elif event & select.EPOLLHUP:
                        print("客户端22:", socket.getpeername(), "CLOSE CONNECT")
                        #在epoll中注销客户端的文件句柄
                        self.epoll.unregister(fd)
                        #关闭客户端的文件句柄
                        fd_to_socket[fd].close()
                        #在字典中删除与已关闭客户端相关的信息
                        del fd_to_socket[fd]
                        time.sleep(10)
                    #可读事件
                    elif event & select.EPOLLIN:
                        #print "11111111111"
                        #接收数据
                        data = socket.recv(1024)
                        if data:
                            print("长度:", len(data), "FD:", fd, "收到数据:", data,
                                  "客户端33:",
                                  socket.getpeername()[0],
                                  socket.getpeername()[1])
                            #处理收到的数据
                            #将数据后的返回值放入对应客户端的字典
                            msg = self.handle_data(data,
                                                   socket.getpeername()[0],
                                                   socket.getpeername()[1], fd)
                            local_socket = fd_to_socket[self.dfd]
                            if local_socket:
                                message_queues[local_socket].put(msg, )

                            #修改读取到消息的连接到等待写事件集合(即对应客户端收到消息后,再将其fd修改并加入写事件集合)
                            #self.epoll.modify(fd, select.EPOLLOUT)
                            # print "发送数据FD:" , self.dfd
                            self.epoll.modify(self.dfd, select.EPOLLOUT)
                        else:
                            print("NO DATA CLOSE CLIENT CONNECTION !!!")
                            self.epoll.unregister(fd)
                            fd_to_socket[fd].close()
                            del fd_to_socket[fd]
                    #可写事件
                    elif event & select.EPOLLOUT:
                        # print "EPOLLOUTEPOLLOUTEPOLLOUTEPOLLOUT"
                        try:
                            #从字典中获取对应客户端的信息
                            msg = message_queues[socket].get_nowait()
                        except queue.Empty:
                            print(socket.getpeername(), " queue empty")
                            #修改文件句柄为读事件
                            self.epoll.modify(fd, select.EPOLLIN)
                        else:
                            print("发送数据:", msg, "客户端66 :",
                                  socket.getpeername(), "fd: ", fd)
                            #发送数据
                            socket.send(msg.encode('utf-8'))

            except Exception as e:
                print(e)
                self.epoll.unregister(fd)
                fd_to_socket[fd].close()
                del fd_to_socket[fd]
Esempio n. 49
0
    local = ('', 8890)
    remote = ('192.168.10.1', 8889)

    signal.signal(signal.SIGINT, signal.SIG_DFL)

    socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket.bind(local)
    socket.setblocking(1)

    out = None

    attempts = 3
    for i in range(attempts):

        socket.sendto('command'.encode('latin-1'), remote)
        buffer = socket.recv(BUFFER_SIZE)
        out = buffer.decode('latin-1')

        if out == 'ok':
            print('accepted')
            break
        else:
            print('rejected')
            time.sleep(0.5)
            out = None
    
    db = TinyDB('data/drone_db.json')
    telemetry = db.table("Telemetry")

    while out:
        buffer = socket.recv(BUFFER_SIZE)
Esempio n. 50
0
    octets = os.path.getsize(nomFich) / 1024
    print(" >> OK : '" + nomFich + "' [" + str(octets) + " Ko]")
    print("")

    print("")
    print(
        " >> Connexion to the server is a success, waiting for a response...")
    print("")

    socket.connect((host, port))
    recu = "NAME " + nomFich + " OCTETS " + str(octets)
    socket.send(recu.encode('utf8'))

    while (socket.connect):

        recu = socket.recv(1024)
        recu = recu.decode('utf8')
        if not recu: break

        if recu == "start":  # If the server accepts we send the file
            print(" >> your request is accepted by the server")
            print(
                time.strftime(
                    " >> [%H:%M] transfer in progress please wait..."))
            print(" ")

            num = 0
            pourcent = 0
            octets = octets * 1024
            fich = open(nomFich, "rb")
Esempio n. 51
0
def readOkay(socket):
    data = socket.recv(4)
    return data[0] == 'O' and data[1] == 'K' and data[2] == 'A' and data[
        3] == 'Y'
Esempio n. 52
0
#!/usr/bin/python3
# coding: utf-8

import socket
import time
hote = "172.24.1.1"
port = 17685

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    socket.connect((hote, port))
except ConnectionRefusedError:
    print("Connection failed")
    quit(0)
print("Connection on {}".format(port))
with open("mesures.txt", "w") as f:
    try:
        while True:
            f.write(socket.recv(100000).decode("utf-8")+"\n")
    except KeyboardInterrupt:
        pass
print("Close")
socket.close()
Esempio n. 53
0
async def run_Game():
    global cat_x, cat_y, live_list
    global X0, Y0, X1, Y1
    global meat_punch_sound
    pyautogui.moveTo(600,1000)  # 마우스 포인터 우측 하단으로 치우기
    cat_x = -500
    cat_y = -500
    cat_xchange = 0
    cat_ychange = 0
    mouse_speed = 10  # 12
    meat_punch_sound = pygame.mixer.Sound(dirpath+'/sound/Meat_Punch01.wav')

    mouse_list = [Fish(True, 0), Fish(False, 1), Fish(False, 2), Fish(False, 3)]
    crashed = False

    moveDetector = MoveDetector()
    while not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    cat_ychange = -5
                elif event.key == pygame.K_DOWN:
                    cat_ychange = 5
                elif event.key == pygame.K_LEFT:
                    cat_xchange = -5
                elif event.key == pygame.K_RIGHT:
                    cat_xchange = 5
                elif event.key == pygame.K_LCTRL:  # 쥐 네마리까지
                    if False in live_list:
                        idx = live_list.index(False)
                        mouse_list[idx].__init__(True, idx)


                elif event.key == pygame.K_LSHIFT:
                    #MouseCount -= 1
                    pass


                elif event.key == pygame.K_q:
                    pass
                    '''
                    for i in range(len(mspeed)):
                        mspeed[i] += 2
                        '''
                elif event.key == pygame.K_a:
                    pass
                    '''
                    for i in range(len(mspeed)):
                        mspeed[i] -= 2
                        '''
                elif event.key == pygame.K_z:
                    pass
                    '''
                    mouse = pygame.image.load('images/mouse.png')
                    mouse = pygame.transform.scale(mouse, (mouse_width, mouse_height))
                    '''
                elif event.key == pygame.K_x:
                    pass
                    '''
                    mouse = pygame.image.load('images/mouse_black.png')
                    mouse = pygame.transform.scale(mouse, (mouse_width, mouse_height))
                    '''

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    cat_ychange = 0
                elif event.key == pygame.K_DOWN:
                    cat_ychange = 0
                elif event.key == pygame.K_LEFT:
                    cat_xchange = 0
                elif event.key == pygame.K_RIGHT:
                    cat_xchange = 0
                elif event.key == pygame.K_ESCAPE:
                    crashed = True

        # 매 프레임마다 이전프레임의 잔상 제거
        #gamepad.fill(WHITE)
        instantiate(background, 0, 0)


        send_data = "receive_cat_info"
        # 통신 ----------------------------------------------------------
        if socket_switch:
            socket.send(send_data.encode())
            recv_data = socket.recv(32).decode("UTF-8")
            data = recv_data.split(" ")
            X0, Y0, X1, Y1 = int(data[0]), int(data[1]), int(data[2]), int(data[3])
        else:
            X0, Y0, X1, Y1 = cat_x, cat_y, cat_x + 50, cat_y + 50
        # 고양이 이동
        cat_x += cat_xchange
        cat_y += cat_ychange

        ncat = pygame.transform.scale(cat, (X1-X0, Y1-Y0))
        instantiate(ncat, X0, Y0)
        moveDetector.update()

        for x in mouse_list:
            x.update()

        # 마지막
        pygame.display.update()
        clock.tick(60)  # 프레임 수
    pygame.quit()
    quit()
Esempio n. 54
0
def command_handler(socket, signal_pack, userinfo):
    logged_in = False  # whether an user is logged in or not
    recipient = ""
    title = ""

    while True:
        send_status = True
        response_status = None
        response_content = None
        packed_response = None

        try:
            recv_command = socket.recv(1024)
        except error as emsg:
            print("Socket recieve error: ", emsg)
            print("Exiting server thread ...")
            sys.exit(1)

        try:
            command_num, command_arg = signal_pack.unpack(recv_command)
        except struct.error as emsg:
            print("Unpack package error: ", emsg)
            print("Exiting server thread ...")
            sys.exit(1)

        decoded_command_arg = command_arg.strip(b'\x00').decode(
            encoding='utf-8')

        if command_num == 0:
            if logged_in == True:
                response_status = 200
                response_content = "Already logged in"
            else:
                userinfo["username"] = decoded_command_arg
                userinfo["password"] = user_password(userinfo["username"])

                if userinfo["password"] is not None:
                    response_status = 250
                    response_content = "Username ok"
                else:
                    response_status = 200
                    response_content = "Username does not exist"

        elif command_num == 1:
            if logged_in == True:
                response_status = 200
                response_content = "Already logged in"
            else:
                if userinfo[
                        "username"] is not None and userinfo["username"] != "":
                    if userinfo["password"] == decoded_command_arg:
                        # success login
                        logged_in = True
                        response_status = 250
                        response_content = "User authenticated"
                    else:
                        response_status = 200
                        response_content = "Authentication failure"
                else:
                    response_status = 200
                    response_content = "Username is missing"

        elif logged_in == True:
            if command_num == 2:
                if decoded_command_arg != "":
                    if user_password(decoded_command_arg) is not None:
                        response_status = 250
                        response_content = "Recipient ok"
                        recipient = decoded_command_arg
                    else:
                        response_status = 200
                        response_content = "Recipient does not exist on the server"
                        recipient = ""
                else:
                    response_status = 200
                    response_content = "Recipient is missing"
                    recipient = ""
            elif command_num == 3:
                if recipient != "":
                    response_status = 250
                    response_content = "Title ok"
                    title = decoded_command_arg
                else:
                    response_status = 200
                    response_content = "Recipient is missing"
                    title = ""
            elif command_num == 4:
                response_status, response_content = write_email(
                    socket, recipient, userinfo["username"], title)
            elif command_num == 5:
                send_status = False
                list_email(socket, userinfo["username"])
            elif command_num == 6:
                send_status = False
                if decoded_command_arg != "":
                    try:
                        n = int(decoded_command_arg)
                        retrieve_email(socket, userinfo["username"], n)
                    except ValueError:
                        try:
                            socket.send(bytes(".", encoding='utf-8'))
                        except error as emsg:
                            print("Send content error: ", emsg)
                            print("Exiting server thread ...")
                            sys.exit(1)
                    except IndexError:
                        try:
                            socket.send(bytes(".", encoding='utf-8'))
                        except error as emsg:
                            print("Send content error: ", emsg)
                            print("Exiting server thread ...")
                            sys.exit(1)
                else:
                    try:
                        socket.send(bytes(".", encoding='utf-8'))
                    except error as emsg:
                        print("Send content error: ", emsg)
                        print("Exiting server thread ...")
                        sys.exit(1)
            elif command_num == 7:
                if decoded_command_arg != "":
                    try:
                        n = int(decoded_command_arg)
                        delete_email(n, userinfo["username"])
                        response_status = 250
                        response_content = "Delete ok"
                    except IndexError as emsg:
                        print("Client deleting email out of range")
                        response_status = 200
                        response_content = "Index of email out of range"
                    except ValueError as emsg:
                        print("Integer convertion error: ", emsg)
                        response_status = 200
                        response_content = "Index of email should be integer"
                    except IOError as emsg:
                        print("File IO error: ", emsg)
                        print("Exiting server thread ...")
                        sys.exit(1)
                    except error as emsg:
                        print("Unexpected error: ", emsg)
                        print("Exiting server thread ...")
                        sys.exit(1)
                else:
                    response_status = 200
                    response_content = "Index of email is missing"
            if command_num == 8:
                try:
                    packed_response = signal_pack.pack(
                        250, bytes("Exit ok", encoding='utf-8'))
                except struct.error as emsg:
                    print("Pack status response error: ", emsg)
                    print("Exiting server thread ...")
                    sys.exit(1)
                try:
                    socket.send(packed_response)
                except error as emsg:
                    print("Send response error: ", emsg)
                    print("Exiting server thread ...")
                    sys.exit(1)

                print("Client disconnected")
                print("Exiting server thread ...")
                sys.exit(0)
        elif logged_in == False:
            if command_num == 5 or command_num == 6:
                try:
                    print(".")
                    socket.send(bytes(".", encoding='utf-8'))
                except error as emsg:
                    print("Send response error: ", emsg)
                    print("Exiting server thread ...")
                    sys.exit(1)
                continue
            else:
                response_status = 200
                response_content = "User not logged in yet"

        print(response_status)
        print(response_content)
        # pack status
        if send_status == True:
            try:
                packed_response = signal_pack.pack(
                    response_status, bytes(response_content, encoding='utf-8'))
            except struct.error as emsg:
                print("Pack status response error: ", emsg)
                print("Exiting server thread ...")
                sys.exit(1)
            try:
                socket.send(packed_response)
            except error as emsg:
                print("Send response error: ", emsg)
                print("Exiting server thread ...")
                sys.exit(1)
def midas_recv(socket):
    address = socket.recv()
    socket.recv()  # Empty sequence
    msg_type = socket.recv_string()
    message = socket.recv_string()
    return address, msg_type, message
Esempio n. 56
0
#while 1:
#TEMPORARY CODE USED TO GENERATE PREDICTABLE OUTPUT COORDINATES
#    randNode = random.randint(0,3)
#    randDest = random.randint(0,3)
#    randCons = random.randint(0,10)
#    cons = 0
#    if randCons >= 7:
#        cons = 1
#    t = t + 1
#    dest = [randDest, t]
#    out = str(nodes[randNode][0]) + ";" + str(nodes[randNode][1]) + ";"
#    nodes[randNode] = dest
#    out = out + str(nodes[randNode][0]) + ";" + str(nodes[randNode][1]) + ";" + str(cons)
#    print(out)
#    EncodeWebSockSend(clientsocket, out)
###############

while 1:
    txt = socket.recv(
        2048
    )  #"" + str(parentx) + ";" + str(parenty) + ";" + str(nodex) + ";"+str(nodey)+";1"
    print txt
    contents = txt.split("\n")
    for cont in contents:
        EncodeWebSockSend(clientsocket, cont)
#clientsocket.send('hello from server')
    print("-----------hello from server sent-------------")
    time.sleep(0.5)

print("done")
Esempio n. 57
0
def recv_listing(socket):
    listing_size = socket.recv(24)
    listing = recv_all(socket, int(listing_size, 2)).decode("utf-8")
    return f"Server's listings are the following: \n {listing}"
import socket
import sys
#socket IPV4 protocolo TCP
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#podemos recorrerlos hasta 254
for host in range(10, 80):
	ports = open('ports.txt', 'r')#abrimos los puertos que queremos escanear
	vulnbanners = open('vulnbanners.txt', 'r')#servicios vulnerables
	for port in ports:#recorremos los puertos
		try:
			socket.connect(( str(sys.argv[1]+'.'+str(host)), int(port) ))#nos conectamos a cada host con el puerto
			print 'Connecting to '+str(sys.argv[1]+'.'+str(host))+' in the port: '+str(port)
			socket.settimeout(1)#esperamos un segundo
			banner = socket.recv(1024)#recuperamos el banner
			for vulnbanner in vulnbanners:
				if banner.strip() in vulnbanner.strip():#si el baner es igual al vulnbanners hay una vulnerabilidad
					print 'We have a winner! '+banner
					print 'Host: '+str(sys.argv[1]+'.'+str(host))
					print 'Port: '+str(port)
		except :# no se esta utilizando el puerto se aumenta en mas 1 sys.argv[1]+
			print 'Error connecting to: '+str(sys.argv[1]+'.'+str(host)) +':'+ str(port)
			pass
Esempio n. 59
0
def recv_header_size(socket):
    header_size = int(socket.recv(24), 2)
    return header_size
Esempio n. 60
0
    int(port)

#if len(sys.argv) > 2:
#    port1 =  sys.argv[2]
#    int(port1)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://10.50.0.52:12345")
if len(sys.argv) > 2:
  socket.connect("tcp://10.50.0.52:12345")

topicfilter = ""
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

while True:
  phrase = socket.recv()
  print phrase
  b2 = literal_eval(phrase)
  for i in range(0, 8):
    if b2[i] == '1':
      GPIO.output(int(buzzlist[i]), True)
      print (b2)
      time.sleep(0.01)
    else:
      GPIO.output(int(buzzlist[i]), False)
      time.sleep(0.01)