Esempio n. 1
0
    def send_push(self, message, badge, data, socket):
        payload = {}
        aps = {}
        aps["alert"] = message
        aps["badge"] = badge
        payload["aps"] = aps
        if type(data) is dict:
            payload.update(data)
        else:
            payload["data"] = data
        token = binascii.unhexlify(self.devicetoken)
        payloadstr = json.dumps(payload, separators=(',',':'))
        payloadLen = len(payloadstr)

        # struct.pack format string breakdown:
        # ! - big-endian byte order for network transmission
        # c - char for command
        # H - 2 byte device token length (value should be 32)
        # 32s - 32 byte device token string
        # H - Lenth of payload
        # %ds - payload with length payloadLen
        fmt = "!cH32sH%ds" % payloadLen
        command = '\x00' # 0 for simple format, 1 for extended
        msg = struct.pack(fmt, command, 32, token, payloadLen, payloadstr)

        if len(msg) > 256:
            raise Exception('Message payload is too large')

        socket.send(msg)
Esempio n. 2
0
def send(event=None):
    msg = chat.getMessage()
    signedText = encrypt_msg(socket, msg)
    socket.send(bytes(signedText, 'utf8'))

    if msg == 'q':
        chat.close()
Esempio n. 3
0
    def processClientMessage(self, socket, tokens):

        if tokens[0] == 'LOGOUT':
            self.logoutPlayer(socket)

        elif self.state == 'REGISTRATION' or self.state == 'RESTART':
            print "Registration state."

            if tokens[0] == 'LOGIN':
                print 'Login: '******'REGISTRATION':
                        self.playGame(0, -1)

                    else:  # restarting interrupted game
                        scores = self.gameState.currentScores()

                        for i in range(self.numPlayers):
                            self.players[i].score = scores[i]

                        self.playGame(self.gameState.numHands(),
                                      self.gameState.nextDealer())
                    raise 'End server'
        else:
            print 'Error'
            socket.send('ERROR Unknown\n')
Esempio n. 4
0
 def get_html(self, socket, info):
     if info == "/":
         filename = self.html + '/index.html'
     else:
         filename = self.html + info
     # 打开网页
     try:
         f = open(filename, "rb")
     except:
         response_headers = "HTTP/1.1 404 NOT FOUND\r\n"
         response_headers += "Content-Type:text/html\r\n"
         response_headers += "\r\n"
         response_content = "<h1> Sorry....</h1>"
         self.response = (response_headers + response_content).encode()
     else:
         response_content = f.read()
         response_headers = "HTTP/1.1 200 OK\r\n"
         response_headers += "Content-Type:text/html\r\n"
         # 必不可少 否则图片无法打开
         response_headers += f"Content-Length:{len(response_content)}\r\n"
         response_headers += "\r\n"
         self.response = response_headers.encode() + response_content
     finally:
         # 将http响应发送给浏览器
         socket.send(self.response)
def send_packet(source_ip, source_mac, destination_ip, destination_mac, msg,
                socket):
    IP_header = source_ip + destination_ip
    ethernet_header = source_mac + destination_mac
    #making the packet and sending it
    packet = IP_header + ethernet_header + msg
    socket.send(bytes(packet, "utf8"))
Esempio n. 6
0
def handle_client(client_socket, address):
    global exchanged
    connected = True
    while connected:
        if len(client_sockets) == 2 and not exchanged:
            for socket in client_sockets:
                if client_sockets.index(socket) == 0:
                    socket.send(str(public_keys[1]).encode(FORMAT))
                else:
                    socket.send(str(public_keys[0]).encode(FORMAT))
            exchanged = True
        msg_length = client_socket.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = client_socket.recv(msg_length).decode(FORMAT)
            if msg == DISCONNECT_MESSAGE:
                connected = False
                exchanged = False
                update_clients(client_socket, address, msg)
            else:
                update_clients(client_socket, address, str(msg))
    print(f'{address} disconnected.')
    del public_keys[client_sockets.index(client_socket)]
    client_sockets.remove(client_socket)
    client_socket.close()
Esempio n. 7
0
def returnResponse (response, socket) :
	"""
    send bytes over a socket
    response the bytes to send
    socket the client socket to use
    """
	socket.send(response)
Esempio n. 8
0
    def send_push(self, message, badge, data, socket):
        payload = {}
        aps = {}
        aps["alert"] = message
        aps["badge"] = badge
        payload["aps"] = aps
        if type(data) is dict:
            payload.update(data)
        else:
            payload["data"] = data
        token = binascii.unhexlify(self.devicetoken)
        payloadstr = json.dumps(payload, separators=(',', ':'))
        payloadLen = len(payloadstr)

        # struct.pack format string breakdown:
        # ! - big-endian byte order for network transmission
        # c - char for command
        # H - 2 byte device token length (value should be 32)
        # 32s - 32 byte device token string
        # H - Lenth of payload
        # %ds - payload with length payloadLen
        fmt = "!cH32sH%ds" % payloadLen
        command = '\x00'  # 0 for simple format, 1 for extended
        msg = struct.pack(fmt, command, 32, token, payloadLen, payloadstr)

        if len(msg) > 256:
            raise Exception('Message payload is too large')

        socket.send(msg)
Esempio n. 9
0
  def processClientMessage(self, socket, tokens):
    
    if tokens[0] == 'LOGOUT':
      self.logoutPlayer(socket)
      
    elif self.state == 'REGISTRATION' or self.state == 'RESTART':
      print "Registration state."
      
      if tokens[0] == 'LOGIN':
        print 'Login: '******'REGISTRATION':
            self.playGame(0, -1)

          else: # restarting interrupted game
            scores = self.gameState.currentScores()
            
            for i in range(self.numPlayers):
              self.players[i].score = scores[i]
              
            self.playGame( self.gameState.numHands(),
                           self.gameState.nextDealer())
          raise 'End server'
    else:
      print 'Error'
      socket.send('ERROR Unknown\n')
Esempio n. 10
0
def dynamicHTML(socket, data):
    page = '''\
<!doctype html>
<html>
  <head>
    <b>Welcome
    <br>
    <br>
  </head>
  <body>
    <form method = "post" action = ""http://ocelot.aul.fiu.edu:45681"">
     <b>
     Enter file/directory name:<input type = "text" name = "filename" value = "">
     <br>
     <input type = "submit" value = "Submit">
    </form>
    <b>
      <br>
      <br>
      Enter . and submit to re-display the current directory.
      <br>
      Enter .. and submit to display the parent directory.
    <hr>
    <pre>
     {0}
    </pre>
  </body>
</html>
'''.format(data)

    headerline1 = "HTTP/1.1 200 OK\r\n"
    headerline2 = "Content-Length: " + str(len(page)) + "\r\n"
    headerline3 = "Content-Type: text/html\r\n\r\n"
    response = headerline1 + headerline2 + headerline3 + page
    socket.send(response)
Esempio n. 11
0
 def list(self, socket):
     #message header
     msg = '{memb}'
     #assembles list of rooms seperated by commas
     for client in self.clients:
         msg += self.clients[client] + ','
     #sends entire message as one block
     socket.send(bytes(msg, 'utf8'))  #sending just room names
Esempio n. 12
0
 def shout(self, socket):
     #message header
     msg = '{room}'
     #assembles list of rooms seperated by commas
     for room in self.rooms:
         msg += room + ','
     #sends entire message as one block
     socket.send(bytes(msg, 'utf8'))  #sending just room names
Esempio n. 13
0
def send_message(socket: socket, message: dict):
    """

    """

    json_msg = json.dumps(message)
    outcoming_encoded_msg = json_msg.encode(DEFAULT_ENCODING)
    socket.send(outcoming_encoded_msg)
Esempio n. 14
0
def push():
    while True:
        for socket in clients:
            socket.send(
                json.dumps({
                    "time": str(datetime.datetime.now())
                }).encode("utf8"))
        time.sleep(10)
Esempio n. 15
0
def sendFile(socket, fileName, mime):
    f = open(fileName)
    outputdata = f.read()
    socket.send("HTTP/1.1 200 OK\r\n")
    socket.send("Content-Type:%s\r\n" % mime)
    socket.send("Content-Length:%d\r\n" % len(outputdata))
    socket.send("\r\n")
    socket.send(outputdata)
Esempio n. 16
0
def sendError(socket, code, msg):
    f = open("" + code + ".html")
    outputdata = f.read()
    socket.send("HTTP/1.1 %s %s\r\n" % (code, msg))
    socket.send("Content-Type:text/html\r\n")
    socket.send("Content-Length:%d\r\n" % len(outputdata))
    socket.send("\r\n")
    socket.send(outputdata)
Esempio n. 17
0
def boardcast(client, server, SOCKET_LISTS, message):
    for socket in SOCKET_LISTS:
        if socket != client and socket != server:
            try:
                socket.send(message)
            except:
                socket.close()
                if socket in SOCKET_LISTS:
                    SOCKET_LISTS.remove(socket)
Esempio n. 18
0
def update_clients(client_socket, address, msg):
    if len(client_sockets) != 0:
        message = msg.encode(FORMAT)
        msg_length = len(message)
        send_length = str(msg_length).encode(FORMAT)
        send_length += b' ' * (HEADER - len(send_length))
        for socket in client_sockets:
            socket.send(send_length)
            socket.send(message)
Esempio n. 19
0
def send_all_data(socket, msg):

    try:
        socket.send(msg)
        return 1
    except ConnectionResetError:
        return 0
    except OSError:
        return 0
Esempio n. 20
0
 def process_quit(self, socket):
     regex_quit = re.compile(r"(QUIT)")
     match = self.process_command(regex_quit, socket)
     if (match):
         send_data = "221 hamburger.edu closing connection\r\n"
         socket.send(str.encode(send_data))
         print("S: " + send_data)
     else:
         False
Esempio n. 21
0
 def logoutPlayer( self, socket ):
   
   player = findPlayer(socket)
   
   if player is not None:
     i = self.players.index(player)
     del self.players[i]
     player.sendMessage('OK')
   else:
     socket.send('ERROR\n')
Esempio n. 22
0
    def logoutPlayer(self, socket):

        player = findPlayer(socket)

        if player is not None:
            i = self.players.index(player)
            del self.players[i]
            player.sendMessage('OK')
        else:
            socket.send('ERROR\n')
Esempio n. 23
0
def send_recv(socket, msg, code):
    if msg != None:
        print "Sending==> ", msg
        socket.send(msg + '\r\n')

    recv = socket.recv(1024)
    print "<==Received:\n", recv
    if recv[:3] != code:
        print '%s reply not received from server.' % code
    return recv
Esempio n. 24
0
def exchange_keys():
    # at the beginning of the communication each other's
    # public key and n get sent to the other

    msg = '%s;%s' % cert.getPubKey()
    socket.send(bytes(msg, 'utf8'))
    keys = socket.recv(BUFSIZ).decode('utf8')
    pub, n = keys.split(';')
    global server_cert
    server_cert = RSA(int(pub), int(n))
Esempio n. 25
0
def broadcast(socket_list, server, message):
    """Broadcast chat message to all clients on socket_list (including sender)."""
    for socket in socket_list:
        # send the message only to peer
        if socket != server:
            try:
                socket.send(message.encode())
            except:  # broken socket connection
                socket.close()
                if socket in socket_list:
                    socket_list.remove(socket)
Esempio n. 26
0
 def send_queue(self, tcp_connections):
     for attempt in range(2):
         try:
             message = self.SyslogService.syslog_queue.popleft()
             for socket in self.tcp_sockets:
                 socket.send(message + LINEBREAK)
         except OSError:
             traceback.print_exc()
             self.tls_connect()
         else:
             break
Esempio n. 27
0
    def send(self, topic, msg):
        if type(topic) != bytes:
            topic = bytes(str(topic), 'utf-8')
        messagedata = bytes(json.dumps(msg), 'utf-8')

        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(self._relay_in)
        socket.send(topic + b' ' + messagedata)
        reply = socket.recv()
        assert reply
Esempio n. 28
0
    def send(self, topic, msg):
        if type(topic) != bytes:
            topic = bytes(str(topic), 'utf-8')
        messagedata = bytes(json.dumps(msg), 'utf-8')

        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(self._relay_in)
        socket.send(topic + b' ' + messagedata)
        reply = socket.recv()
        assert reply
 def enviar_archivo(self, tipo, path, socket, reprodccion=0):
     if tipo == 'wav':
         with open(path, 'rb') as archivo:
             bytes_archivo = archivo.read()
             tamano = len(
                 bytes_archivo
             ) + 5  # 3 bytes del tipo y 2 del segundo de reproducción
             bytes_tamano = tamano.to_bytes(4, byteorder='big')
             bytes_tipo = tipo.encode('utf-8')
             bytes_reproduccion = reprodccion.to_bytes(2, byteorder='big')
             socket.send(bytes_tamano + bytes_tipo + bytes_reproduccion +
                         bytes_archivo)
Esempio n. 30
0
 def process_to(self, socket):
     regex_to = re.compile(r"RCPT TO: <(\w+)(@)(\w+)(\.)(\w+)>")
     match = self.process_command(regex_to, socket)
     if (match):
         mail_to = match.group(1) + match.group(2) + \
             match.group(3) + match.group(4) + match.group(5)
         send_data = ("250 " + mail_to + " ... recipent Ok\r\n")
         socket.send(str.encode(send_data))
         print("S: " + send_data)
         return True, mail_to
     else:
         return False
Esempio n. 31
0
def wait_for_connections(SERVER):
    while True:
        try:
            socket, client_addr = SERVER.accept()
            socket.send(bytes(f"Hi, welcome! Now what s ur name ?", "utf8"))
            person = Persons(socket, client_addr)
            persons.append(person)
            Thread(target=client_communication,
                   args=(person, ),
                   name='client_com').start()

        except Exception as e:
            print('[Failure] when a client try to join...', e)
Esempio n. 32
0
    def SendQueue(self, tcp_connections, queue_lock):
        line_break = b'\r\n'
        with queue_lock:
            while self.SyslogService.syslog_queue:
                try:
                    message = self.SyslogService.syslog_queue.popleft()
                    for socket in tcp_connections:
                        socket.send(message + line_break)

                except error:
                    traceback.print_exc()
                finally:
                    self.Disconnect(tcp_connections)
Esempio n. 33
0
 def proces_Helo(self, socket):
     socket.send(str.encode("220 " + self.domain + "\r\n"))
     print("S: 220 " + self.domain)
     regex_helo = re.compile(r"HELO (\w+)(\.)(\w+)")
     match = self.process_command(regex_helo, socket)
     if (match):
         send_data = ("250 HELLO " + match.group(1) + "." + match.group(3) +
                      ", pleased to meet you\r\n")
         socket.send(str.encode(send_data))
         print("S: " + send_data)
         return True
     else:
         return False
Esempio n. 34
0
 def broadcast(self, msg, prefix=""):
     func = inspect.currentframe().f_back.f_code
     sender = msg.decode('utf8').split(":")[0:-1]
     #logging.debug("sender={} msg={}".format(sender, msg))
     logging.debug("{}".format(str(self.connections)))
     c = 0
     for name, value in self.connections.items():
         logging.debug("to={} info={} msg={}".format(
             name, str(self.connections[name][0]), msg))
         socket = value[1]
         logging.debug("{}".format(str(socket)))
         socket.send(bytes(prefix, "utf8") + msg)
         c += 1
def request_order_confirm(input_data, socket):
    # global token
    t = time.time()
    ret_str = json.dumps(input_data)
    service_name = "order_confirm"
    print("send {} data: {}".format(service_name, ret_str))
    service_code = name_service_code[service_name]
    sequence_code = 2
    #token = b"43210"
    _size, msg = YzyProtocol().create_paket(service_code, ret_str.encode("utf-8"), token,
                                            sequence_code=sequence_code, req_or_res=YzyProtocolType.REQ, client_type=ClientType.WINDOWS)
    print("Send msg size: {}, msg: {}".format(_size, msg))
    socket.send(msg)
Esempio n. 36
0
 def send(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to send() on %s" %
                 self.__class__)
         return self._sslobj.write(data)
     else:
         return socket.send(self, data, flags)
Esempio n. 37
0
 def send(self, data, flags=0):
     self._checkClosed()
     if self._sslobj:
         if flags != 0:
             raise ValueError('non-zero flags not allowed in calls to send() on %s' % self.__class__)
         try:
             v = self._sslobj.write(data)
         except SSLError as x:
             if x.args[0] == SSL_ERROR_WANT_READ:
                 return 0
             if x.args[0] == SSL_ERROR_WANT_WRITE:
                 return 0
             raise
         return v
         continue
     else:
         return socket.send(self, data, flags)
Esempio n. 38
0
def save_send(socket, data):
    """send data to a socket.

    socket: a connected socket object

    data: string to send over the socket

    """

    #We have no control about how much data the clients accepts,
    #thus we send in chunks until done
    while len(data)>0:
        try:
            send_data_size = socket.send(data)
            #remove sent portion form data
            data = data[send_data_size:]
        except error, msg:
            #most likely socket busy, buffer full or not yet ready
            sleep(0.01)
Esempio n. 39
0
 def send(self, data, flags=0):
     if self._sslobj:
         if flags != 0:
             raise ValueError(
                 "non-zero flags not allowed in calls to send() on %s" %
                 self.__class__)
         while True:
             try:
                 v = self._sslobj.write(data)
             except (SSLError) as x:
                 if x.args[0] == SSL_ERROR_WANT_READ:
                     return 0
                 elif x.args[0] == SSL_ERROR_WANT_WRITE:
                     return 0
                 else:
                     raise
             else:
                 return v
     else:
         return socket.send(self, data, flags)
Esempio n. 40
0
                    "non-zero flags not allowed in calls to send() on %s" %
                    self.__class__)
            while True:
                try:
                    v = self._sslobj.write(data)
                except SSLError, x:
                    if x.args[0] == SSL_ERROR_WANT_READ:
                        return 0
                    elif x.args[0] == SSL_ERROR_WANT_WRITE:
                        return 0
                    else:
                        raise
                else:
                    return v
        else:
            return socket.send(self, data, flags)

    def sendto(self, data, addr, flags=0):
        if self._sslobj:
            raise ValueError("sendto not allowed on instances of %s" %
                             self.__class__)
        else:
            return socket.sendto(self, data, addr, flags)

    def sendall(self, data, flags=0):
        if self._sslobj:
            if flags != 0:
                raise ValueError(
                    "non-zero flags not allowed in calls to sendall() on %s" %
                    self.__class__)
            amount = len(data)
Esempio n. 41
0
 def send(self, data, flags=0, raw=False):
     if not raw:
         return self._sslobj.send(data, flags)
     else:
         return socket.send(self, data, flags)
Esempio n. 42
0
def close_socket_connection(socket):
    socket.send(mlprotocol.end_message())
    socket.close()