def _socketRequest(self, scheme, host, port, payload): socket = self._getSocketForScheme(scheme) socket.connect((host, port)) socket.sendall(payload) data = socket.recv(1024) socket.close() return data
def parse_sent_data(data, socket): if data[0:9] == 'userName/': # Username the client chose for himself user_connected = data[9:len(data)] dup = False # Check if it is a duplicate for key, val in user_dic: if user_dic[key, val] == user_connected: dup = True; break if (dup): socket.sendall(str("DUPNAME")) return None # Add to the client dicionary the userName as value and the sockname as key update_user_list(socket.getpeername(), user_connected) return None elif data[0:10] == '--userList': # User requested the user list of the site user_names_to_return = []; for (sock_String, port_value) in user_dic: user_names_to_return.append(user_dic[(sock_String, port_value)]) socket.sendall(str(user_names_to_return)) return None elif data == "CLOSEDCONNECTION": # Client has signaled it is disconnecting remove_client(socket) return None else: return data
def _writeWrapper(self, socket, data): try: socket.sendall(bytes(data + "\r\n", 'utf-8')) except OSError: self.shutdown() raise
def sendAllInt(socket, integerData): try: strLen = struct.pack('i', integerData) socket.sendall(strLen) except socket.error as msg: return False return True
def push(self, metrics, socket=None, logging_prefix=''): """ :param metrics: An iterable of string, each repreasenting a metric data """ """A list of strings representing metrics""" docs = list() for metric in metrics: if metric == 'version' and socket is not None: socket.sendall( (VERSION + '\n').encode() ) line = self.parser.parse(metric, logging_prefix=logging_prefix) if line is None: continue self.lock.acquire() self.buffer.append({'_index': self.index, '_type': line[0], '_source': line[1]}) current_time = time.time() if len(self.buffer) > self.buffer_size or (current_time - self.last_flush) > 60: self.flush() self.last_flush = current_time self.lock.release()
def mangodb(socket, address): socket.sendall('HELLO\r\n') client = socket.makefile() output = open(os.devnull, 'w') lock = threading.Lock() wait = threading.Condition(lock) while 1: line = client.readline() if not line: break cmd_bits = line.split(' ', 1) cmd = cmd_bits[0] if cmd == 'BYE': break if cmd == 'WAIT': wait.wait() continue if len(cmd_bits) > 1: lock.acquire(True) output.write(cmd_bits[1]) if MANGODB_DURABLE: output.flush() os.fsync(output.fileno()) data = '42' if MANGODB_EVENTUAL else \ os.urandom(1024).encode('string-escape') lock.release() client.write('OK' + data + '\r\n') client.flush()
def round(self, player, move): """ """ if (move[0] == constants.QUIT): self.set_game_in_progress(False) #TODO: make something to the end of the game elif (move[0] == constants.CLICK): # verifies if is the player's turn if (player != self.get_player()): pass # verifies if is a empty square elif (self.board.getSquare(move[1]) != 0): pass else: try: self.board.setSquare(move[1], self.player_indice + 1) self.board.display() msg = serialize.dumps((constants.DRAW, move[1], self.get_color())) ignore, ready, ignore2 = select.select([], self.players, [], 0) # checks if we have a winner if self.end_game(move[1]): self.set_game_in_progress(False) print "end of the game" # Draws the winner msg = serialize.dumps((constants.WINNER, self.get_winner_coordinates(), self.get_color())) ignore, ready, ignore2 = select.select([], self.players, [], 0) for socket in ready: socket.sendall(msg) else: for socket in ready: socket.sendall(msg) self.next_player() finally: self.server.close()
def buildpath(socket, basedir, httpid): """Builds a directory path to a file from an HTTP request.""" request = socket.recv(4096) print str(httpid) + " REQUEST" print "Request recieved: " + request reqlist = request.split() print "Request in list form: " + str(reqlist) print "Length of reqlist: " + str(len(reqlist)) if (len(reqlist) > 1): if (reqlist[0] == "GET"): endpath = reqlist[1] abspath = basedir + str(endpath) print "Full path constructed: " + str(abspath) print (endpath) else: socket.sendall("HTTP/1.0 400 Bad Request\r\n") socket.close abspath = None else: socket.sendall("HTTP/1.0 400 Bad Request\r\n") socket.close abspath = None return abspath
def send_message(self, socket, data): try: socket.sendall(data) #except socket.error, e: except Exception, (error, message): print 'Error sending data. Exiting...' sys.exit()
def serviceClientsOut(self): while 1: self.commandsEvent.wait() try: ###dispatch individual commands self.indivCommandsLock.acquire() while self.indivCommands: self.socketsLock.acquire() socket = self.sockets[self.indivCommands[0][0]] socket.sendall(self.indivCommands[0][1]+self.term) self.socketsLock.release() self.indivCommands.pop(0) self.indivCommandsLock.release() ### dispatch commands to each socket connected self.commandLock.acquire() while self.commands: self.socketsLock.acquire() for socket in self.sockets.values(): socket.sendall(self.commands[0]+self.term) self.socketsLock.release() if BotWars.DEBUG: print "server send: "+self.commands[0] pass self.commands.pop(0) self.commandLock.release() self.commandsEvent.clear() ###capture disconnects and remove those sockets from the list ### release any locked locks ### kill service thread if no more sockets remain except error , se: self.handleError(socket)
def sendRequest(self, socket): print "Sending request to server\n" HTTPcommand = sys.argv[3] filePath = sys.argv[4] if HTTPcommand in validHTTPRequestGet : socket.send(HTTPcommand + " " + filePath + " "+ HTTPprotocol + CRLF ) size = 1024 data = "" while True : recvBuffer = socket.recv(size) if recvBuffer == None or len(recvBuffer) == 0: break; data += recvBuffer socket.close() print 'Received:', data elif HTTPcommand in validHTTPRequestPut: if filePath == "/" : filePath = "/index.html" fileHandler = open("../WebContent" + filePath, "r") print "Reading data from file to send payload to server\n" payload = fileHandler.read() fileHandler.close() putRequest = HTTPcommand + " " + filePath + " " + HTTPprotocol + CRLF + "Host: my simple client" + CRLF + CRLF + "data=" + payload socket.sendall(putRequest) print "Sent data to server\n " socket.close() else: print "Bad request" socket.close()
def send(socket, message): # Send the length of the message. # Should work as long as we send messages shorter than ~10 googol chars length = str(len(message)).encode('utf-8') socket.sendall(length) # Send the message socket.sendall(message.encode('utf-8'))
def send(request, socket): try: socket.sendall(request.encode('utf-8')) socket.sendall(b'\n') except Exception as e: service_down(message=str(e), exception=e) raise e
def checkConnection(socket) : global username socket.sendall(SECURITY_PASS + '\n' + username) reply = socket.recv(1024) log('Received ' + reply) con = reply == OK_MESSAGE return con
def servicerequest(path, socket, httpid): """Services an HTTP request based on the provided file path""" if (os.path.exists(path)): print str(httpid) + " DELIVERED" fd = open(path, "r") file = fd.read() okmsg = "HTTP/1.0 200 OK\r\n" now = datetime.datetime.now() datestr = now.strftime("%a %d %B %Y %H:%M:%S %z") + "\r\n" print "Date and time: " + datestr server = "Server: Var http-server 1.0\r\n" connection = "Connection: close\r\n" content_length = "Content length: " + str(sys.getsizeof(file)) + "\r\n" content_type = "Content type: " + mimetypes.guess_type(path)[0] + "\r\n\r\n" print content_type print content_length header = datestr + server + connection + content_length + content_type socket.sendall(okmsg + header + file) socket.close() else: print str(httpid) + " NOTFOUND" socket.sendall("HTTP/1.0 404 Not Found\r\n") socket.close() print str(httpid) + " CLOSE" return None
def sendFile(fname, socket): blockSize = 32000 msg = '' try: source = open(fname, 'rb') sizeBytes = os.path.getsize(fname) utils.log('Sending file ' + fname + ' of ' + str(sizeBytes) + ' bytes') bytesOut = 0 start = utils.getUTCTime() prev = 0 for data in utils.chunked(source, blockSize): utils.log('sending data ' + str(len(data))) socket.sendall(data) bytesOut += len(data) if (bytesOut - sizeBytes) > 1024: utils.log('WARNING - truncating send because send file appears to be growing.') break; diff = utils.getSecondsBetweenTwoDates(start, utils.getUTCTime()) diff = (int(diff/30))*30 if diff > prev: prev = diff utils.log('So far sent ' + str(bytesOut) + ' read') utils.log('Completed send of ' + str(bytesOut) + ' bytes') socket.settimeout(20) c = socket.recv(4096) utils.log('Received ' + repr(c)) return msg #except(socket.error): #utils.log("timeout in sendFile - possibly no received confirmation data") except Exception, errorcode: if errorcode[0] != "timed out": utils.logTrace('Exception ' + repr(errorcode))
def client(self,socket,addr): infoName="SocketWriter-%s"%(unicode(addr),) self.setName("[%s]%s-Writer %s"%(AVNLog.getThreadId(),self.getName(),unicode(addr))) self.setInfo(infoName,"sending data",AVNWorker.Status.RUNNING) if self.getBoolParam('read',False): clientHandler=threading.Thread(target=self.clientRead,args=(socket, addr)) clientHandler.daemon=True clientHandler.start() filterstr=self.getStringParam('filter') filter=None if filterstr != "": filter=filterstr.split(',') try: seq=0 socket.sendall("avnav_server %s\r\n"%(VERSION)) while True: hasSend=False seq,data=self.feeder.fetchFromHistory(seq,10) if len(data)>0: for line in data: if NMEAParser.checkFilter(line, filter): socket.sendall(line) hasSend=True else: time.sleep(0.1) pass if not hasSend: #just throw an exception if the reader potentially closed the socket socket.getpeername() except Exception as e: AVNLog.info("exception in client connection %s",traceback.format_exc()) AVNLog.info("client disconnected") socket.close() self.removeHandler(addr) self.deleteInfo(infoName)
def sokect_handler(self, socket, address): if self.debug and logger.is_debug(): logger.get_logger().debug('%s: accept connection', address) # send welcome socket.sendall(Messager.data_for_welcome()) conn_inbox = Queue() answer_thread = gevent.spawn(self.answer_fiber, socket, address, conn_inbox) while self._running: try: message = Messager.receive_msg(socket) if not message: if self.debug and logger.is_debug(): logger.get_logger().debug('%s: connection has been closed by client.', address) break; if isinstance(message, Answer): logger.get_logger().error('%s: unexpected message received: %s', address, message) continue elif isinstance(message, Query): if self.debug and logger.is_debug(): logger.get_logger().debug('%s: message received: %s', address, message) message.inbox = conn_inbox self._query_queue.put(message) except gevent.socket.error as ex: logger.get_logger().error('%s: socket error: %s', address, repr(ex)) break except: logger.get_logger().error('%s: exception: %s', address, traceback.format_exc()) break if self.debug and logger.is_debug(): logger.get_logger().debug('%s: close connection', address) socket.close() # stop answer thread conn_inbox.put(StopIteration)
def POST(self, url, args=None): host, port, path = self.parse_url(url) socket = self.connect(host, port) if args == None: arguments = "" else: arguments = urllib.urlencode(args) request = "POST %s HTTP/1.1\n" % path request += "Host: %s\n" % host request += "Content-Type: application/x-www-form-urlencoded\n" request += "Content-Length: %s\n" % len(arguments) request += "Connection: close" + self.TERMINATE request += arguments + self.TERMINATE socket.sendall(request) response = self.recvall(socket) socket.close() code = self.get_code(response) #body = self.get_post_body(response, args) body = self.get_body(response) print response return HTTPRequest(code, body)
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 "=========================================================="
def handler(self, socket, address): try: socket.sendall(self.policy) gevent.sleep(0.5) except Exception: pass finally: socket.close()
def sendAudio(socket,stream,CHUNK): frames = [] while True : data = stream.read(CHUNK) frames.append(data) socket.sendall(data)
def handle_list_request(self, socket): """ envia a lista de arquivos disponíveis (como um objeto) """ print "Enviando lista de arquivos a (%s:%s)" % socket.getpeername() # fazendo dump do objeto (serializando) para bytes list_dump = pickle.dumps(self.file_list, -1) socket.sendall(list_dump) # atendeu à requisição, fecha a conexão self.close_conn(socket)
def test_connection(self, socket): result = True try: socket.sendall("test") except Exception as e: result = False return result
def send_http_error(socket, content, status=None): status = status or "500 Internal Error" data = """HTTP/1.1 {0}\r\nContent-Length: {1}\r\nConnection: close\r\n\r\n{2} """.format( status, len(str(content)), content ).strip() socket.sendall(data) socket.close() logging.debug("!{0}".format(content.lower()))
def _set_cmdmanager_response(self, socket, message): """ Makes cmd_manager response encoding it in json format and send it to cmd_manager """ response = {'message': message} response_packet = json.dumps(response) socket.sendall(struct.pack('!i', len(response_packet))) socket.sendall(response_packet) return response_packet
def send(CONNECTION_LIST1, RaspServer, sock, message): for socket in CONNECTION_LIST1: if socket != RaspServer: try: message = message.encode(encoding='UTF-8') socket.sendall(message) except: socket.close() CONNECTION_LIST1.remove(socket)
def setspeed(self,socket,speed): if speed>=0 and speed<=3: self.cmd=b'\x99' self.datalen=1 self.CMFrame(chr(1+int(speed))) socket.sendall(self.FullFrame()) time.sleep(0.25) self.getfanconfig(socket) return self
def sendMRLCOMMMsg(self, method, value): socket = bpy.mrl.virtualDevices[self.name].serialHandler.request print("sending bytes") print(bytes([170, method, 1, value])) # MRLCOMM PROTOCOL # MAGIC_NUMBER|NUM_BYTES|FUNCTION|DATA0|DATA1|....|DATA(N) # NUM_BYTES - is the number of bytes after NUM_BYTES to the end socket.sendall(bytes([170, 2, method, value]))
def fun_sendall(sc,sock,msg): for socket in socket_list: if(socket != sc and socket != sock): try: socket.sendall(msg) except: socket.close() if(socket in socket_list): print('rm user') socket_list.remove(socket)
def receive_message(self, socket): """Read a socket for messages. Blocks, so only call if selected.""" user = self.users[socket] # Throws IOError when client disconnects. message = socket.recv(BUF_SIZE).decode() if message == '': # Empty message indicates closed socket. self.disconnect(socket) else: try: head, tail = decode_message(message) except ValueError: return if head == 'name': # TODO: Add a notification message for name change malt.log("Renaming {} to {}.".format(str(user), tail)) user.name = tail elif head == 'message': self.record(user, tail) malt.log("{}: '{}'.".format(user.name, tail)) elif head == 'read': malt.log("Reading messages to {}.".format(user.name)) socket.sendall('\0'.join(user.pending).encode()) user.pending = []
def send_message(self, msg: bytes, send_to_hosts: bool, is_control_channel: bool) -> None: if IGNORE_INPUT_DEVICES and not send_to_hosts and not is_control_channel and self.hid_devices is not None: asyncio.run_coroutine_threadsafe( self.hid_devices.send_message_to_devices(msg), loop=self.loop) return targets: List[BluetoothDevice] = self.__get_current_host_as_list( ) if send_to_hosts else self.connected_devices for target in list(targets): try: socket = target.control_socket if is_control_channel else target.interrupt_socket if socket is not None: socket.sendall(msg) except Exception: print("Cannot send data to socket of ", target.object_path, ". Closing") if target is not None: try: target.disconnect_sockets() except: print("Error while trying to disconnect sockets") asyncio.run_coroutine_threadsafe( target.reconcile_connected_state(1), loop=self.loop)
def init_card(socket, socket1, socket2): SET = [0 for i in range(20)] SET1 = [0 for i in range(20)] SET2 = [0 for i in range(20)] for i in range(0, 17): SET[i] = POKER[i] #poker的0到16号 SET1[i] = POKER[i + 17] #poker的17到34 SET2[i] = POKER[i + 34] #poker的34到51 print('SET:') print(sorted(SET)) print('SET1') print(sorted(SET1)) print('SET2') print(sorted(SET2)) json = {'status': 200, 'Operation': 'init', 'Card': [0], 'message': SET} json1 = {'status': 200, 'Operation': 'init', 'Card': [0], 'message': SET1} json2 = {'status': 200, 'Operation': 'init', 'Card': [0], 'message': SET2} socket.sendall(str.encode(str(json))) socket1.sendall(str.encode(str(json1))) socket2.sendall(str.encode(str(json2)))
def kill_network(self, selector_obj): #kill switch for whole network -> ends Server [OPTIONAL] and all clients self.stream_print( "KILL SWITCH RECIEVED. NOTIFYING ALL SINKS AND SOURCES") msg = b'KILL STREAM' self.stream_print("\tNotifiying %d UNDECLARED sockets and removing" % (len(self.undeclared_sockets))) while (len(self.undeclared_sockets) > 0): socket = self.undeclared_sockets[0] try: socket.sendall(msg) except: self.stream_print("ERROR NOTIFYING" + self.print_socket(socket) + " -> BROKEN PIPE ON THEIR END") self.close_socket(socket, selector_obj) self.stream_print("\tNotifiying %d SINK sockets and removing" % (len(self.sink_sockets))) while (len(self.sink_sockets) > 0): socket = self.sink_sockets[0] try: socket.sendall(msg) except: self.stream_print("ERROR NOTIFYING" + self.print_socket(socket) + " -> BROKEN PIPE ON THEIR END") self.close_socket(socket, selector_obj) self.stream_print("\tNotifiying %d SOURCE sockets and removing" % (len(self.src_sockets))) while (len(self.src_sockets) > 0): socket = self.src_sockets[0] try: socket.sendall(msg) except: self.stream_print("ERROR NOTIFYING" + self.print_socket(socket) + " -> BROKEN PIPE ON THEIR END") self.close_socket(socket, selector_obj) if (not (self.mode & SRC2SINK)): pass else: self.store_buffer(SRC2SINK) self.clear_buffer(SRC2SINK) if (not (self.mode & SINK2SRC)): pass else: self.store_buffer(SINK2SRC) self.clear_buffer(SINK2SRC) self.print_state()
def __send_msg(socket, msg): """ 发送消息 :param socket: :param msg: :return: """ msg_str = msg if type(msg) != 'str': msg_str = json.dumps(msg) msg_bytes = bytearray(msg_str, 'utf-8') msg_bytes_len = len(msg_bytes) # 数字转字符数组 msg_bytes_len_bytes = bytearray(struct.pack(">I", msg_bytes_len)) msg_result = msg_bytes_len_bytes + msg_bytes socket.sendall(msg_result) re = socket.recv(3096) return bytearray(re)[4:].decode()
def _tcp_logger(self, socket): """ Checks for messages from TCP client (mic.) and puts them in queue """ sent_stop_msg = False # loop until motors have stopped, mic is stopped and all data is queued while True: # send 'Stop' msg to client (mic.) if motors have stopped if self._mav_stopped and not sent_stop_msg: self._print_fancy("Stopping mic...") socket.sendall(b"STOP") sent_stop_msg = True # check for new data tcp_msg = socket.recv(int(self._mic_blocking_size)) if tcp_msg: # put data in queue self._q_mic.put(tcp_msg) else: # check if motors have stopped if self._mav_stopped: self._print_fancy("All mic. data received.") break # update the mic status for the main thread (collect_data) self._mic_stopped = True
def keyboard_to_socket(socket): """Reads data from keyboard and sends it to the passed socket. Returns number of bytes sent, or 0 to indicate the user entered "EXIT" """ print("You: ", end="", flush=True) # Use end="" to avoid adding a newline after the prompt, flush=True to force-print the prompt # Read a full line from the keyboard. The returned string will include the terminating newline character. user_input = sys.stdin.readline() if user_input == "EXIT\n": # The user requested that the communication is terminated. return 0 # Send the whole line through the socket; remember, TCP provides no guarantee that it will be delivered in one go. bytes_sent = socket.sendall(str.encode(user_input)) return bytes_sent
def wysylanie_danych(name, socket): while True: order = [0, 0, 0, 0, 0, 0] order_str = "" print("Podaj katy o jakie powinny przesunac sie silniki: \n") order[0] = input("Os 1: ") order[1] = input("Os 2: ") order[2] = input("Os 3: ") order[3] = input("Os 4: ") order[4] = input("Os 5: ") order[5] = input("Os 6: ") for x in range(len(order)): order_str = order_str + str(order[x]) if x < len(order) - 1: order_str = order_str + "/" try: socket.sendall(bytes(order_str, 'utf-8')) except Exception as e: print(e) finally: logging.info('Data successfully sent! /from thread: ' + name) print('data sent...')
def connect(self, socket): conn, cursor = self.create_conn() while True: try: msg = socket.recv(1024) msg = json.loads(msg.decode()) result = {'code': 0, 'result': {}} dateall = msg['date'] field = msg['field'] for date in dateall: result['result'][date] = {} sql = self.set_sql(date, field) cursor.execute(sql) receive = cursor.fetchone() for i in range(len(field)): result['result'][date][field[i]] = receive[i] result = json.dumps(result) socket.sendall(result.encode('UTF-8')) except Exception as e: print(e) cursor.close() conn.close() self.close() return
def send(self, socket: socket.socket, protocol: str, data: t.Optional[dict] = None, network_protocol: int = TCP): if network_protocol != self.TCP and network_protocol != self.UDP: raise TypeError( "Invalid network_protocol type. Must be TCP or UDP.") if data is None: data = {} message = self.encoder.encode({"protocol": protocol, "data": data}) if network_protocol == self.TCP: header = bytes(f"{len(message):<{self._header_size}}", "utf-8") socket.sendall(header + message) else: if socket not in self._udp_addresses.keys(): print( "Cannot send packet to user as UDP port has not yet been assigned." ) return address = self._udp_addresses[socket] self._socket_udp.sendto(message, address)
def chatloop(socket): while True: while True: data = tostr(sock.recv(512)) if data == 'ok': sock.sendall(bytes('ok', 'utf-8')) break else: data = data sock.sendall(bytes(data, 'utf-8')) data1 = data if data1 == 'stop': time.sleep(0.05) socket.sendall(bytes('stop received', 'utf-8')) break if data1 != '': if data1[0:9] == 'request: ': data1 = data1[9:] answer = input(data1 + ' :') socket.sendall(bytes(answer, 'utf-8')) else: print(data1) else: pass
def process(socket): print("Going to do handshake... ") k = handshake(socket) if k is None: print("FAILED.") return False print("done.") while True: pt = input("Client message: ") if len(pt) > 0: msg_to_send = encrypt(k, pt.encode("utf-8")) print("encrypted msg:", msg_to_send) socket.sendall(msg_to_send) else: socket.close() break try: data = socket.recv(SOCKET_READ_BLOCK_LEN) pt = decrypt(k, data) print(pt.decode("utf-8")) except: print("You have been disconnected from the server") break
def send_packet(self, msg, direction, selector_obj): if (direction & SRC2SINK == SRC2SINK): if (not (self.mode & SRC2SINK)): self.stream_print("NO SRC2SINK ACCESS") return self.stream_print("Sending Packet from SRC(s) -> SINK(s)") for socket in self.sink_sockets: try: socket.sendall(msg) except: #Broken Pipe error; Socket no longer connected self.close_socket(socket, selector_obj) if (direction & SINK2SRC == SINK2SRC): if (not (self.mode & SINK2SRC)): self.stream_print("NO SINK2SRC ACCESS") return self.stream_print("Sending Packet from SINK(s) -> SRC(s)") for socket in self.src_sockets: try: socket.sendall(msg) except: #Broken Pipe error; Socket no longer connected self.close_socket(socket, selector_obj)
def run(self): if self.enable_tls: context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.check_hostname = False socket = context.wrap_socket(self.socket, server_hostname=self.upstream_ip) else: socket = self.socket try: socket.connect((self.upstream_ip, self.upstream_port)) print("flowmodgenerator connected!") except socket.error as e: if e.errno != 115 and e.errno != 36: print("failed to connect: " + str(e)) return socket.setblocking(False) time.sleep(1) while True: ready_to_read, ready_to_write, error = select.select([socket], [socket], [], TIMEOUT_S) if ready_to_write: message = self.messageGenerator.generate_benchmark_message( self.current_xid) socket.sendall(message) self.current_xid += 1 if self.should_stop: break time.sleep(0.01) socket.close()
def telnet_process_options(self, socket, cmd, opt): IS = b'\00' if cmd == WILL and opt == ECHO: # hex:ff fb 01 name:IAC WILL ECHO description:(I will echo) socket.sendall(IAC + DO + opt) # hex(ff fd 01), name(IAC DO ECHO), descr(please use echo) elif cmd == DO and opt == TTYPE: # hex(ff fd 18), name(IAC DO TTYPE), descr(please send environment type) socket.sendall(IAC + WILL + TTYPE) # hex(ff fb 18), name(IAC WILL TTYPE), descr(Dont worry, i'll send environment type) elif cmd == SB: socket.sendall(IAC + SB + TTYPE + IS + self.env_term.encode() + IS + IAC + SE) # hex(ff fa 18 00 b"VT100" 00 ff f0) name(IAC SB TTYPE iS VT100 IS IAC SE) descr(Start subnegotiation, environment type is VT100, end negotation) elif cmd == SE: # server letting us know sub negotiation has ended pass # do nothing else: print('Unexpected telnet negotiation')
def send_categorical_matrix(socket, categorical_matrix): """ Sends a list of strings to the getml engine (an actual string, not a bytestring). """ if len(categorical_matrix.shape) == 1: shape = [categorical_matrix.shape[0], 1] elif len(categorical_matrix.shape) > 2: raise Exception( "Numpy array must be one-dimensional or two-dimensional!") else: shape = categorical_matrix.shape # By default, numeric data sent over the socket is big endian, # also referred to as network-byte-order! if sys.byteorder == 'little': # Sends the shape of the categorical matrix. socket.sendall( np.asarray(shape).astype(np.int32).byteswap().tostring()) # Sends the length of the encoded string, followed by the encoded string # itself. socket.sendall(''.encode().join([ np.asarray(len(elem.encode('utf-8'))).astype( np.int32).byteswap().tostring() + elem.encode('utf-8') for elem in categorical_matrix.astype(str).flatten() ])) else: # Sends the shape of the categorical matrix. socket.sendall(np.asarray(shape).astype(np.int32).tostring()) # Sends the length of the encoded string, followed by the encoded string # itself. socket.sendall(''.encode().join([ np.asarray(len(elem.encode('utf-8'))).astype(np.int32).tostring() + elem.encode('utf-8') for elem in categorical_matrix.astype(str).flatten() ]))
def inizio_asta(self, senders_socket): global start for client in self.clients_list: socket, (ip, port) = client socket.sendall(self.last_received_message.encode('utf-8')) mess = f"inizio L'asta per {nomecalciatore} è iniziata" socket.sendall(mess.encode('utf-8')) time.sleep(1) #mes = "" mess1 = f"offerta {player_offre}: 1 " socket.sendall(mess1.encode('utf-8')) #mess1 = "" start = time.time()
def single_connection_handler(socket, address): while True: data = socket.recv(2048).decode('utf-8') if data.startswith("HELO"): socket.sendall("{0}\nIP:{1}\nPORT:{2}\nStudentID:{3}".format(data.strip(), "134.226.32.10", str(address[1]), "12326755")) continue elif data.startswith("KILL_SERVICE"): socket.close() break data = data.split('\n') action_key_val = data[0] action_name = action_key_val[:action_key_val.find(':')] if (action_name == 'CHAT'): room_id = int(data[0].split(":")[1]) chatroom_join_id = int(data[1].split(":")[1]) client_name = data[2].split(":")[1] boradcast_message(room_id, "CHAT:{0}\nCLIENT_NAME:{1}\nMESSAGE:{2}\n\n".format(str(room_id), str(client_name), data[3].split(":")[1])) elif (action_name == 'JOIN_CHATROOM'): client_name = data[3].split(":")[1] room_name = data[0].split(":")[1] room_id = int(md5(room_name).hexdigest(), 16) chatroom_join_id = int(md5(client_name).hexdigest(), 16) if room_id not in rooms: rooms[room_id] = dict() if chatroom_join_id not in rooms[room_id]: rooms[room_id][chatroom_join_id] = socket socket.sendall("JOINED_CHATROOM:{0}\nSERVER_IP:{1}\nPORT:{2}\nROOM_REF:{3}\nJOIN_ID:{4}\n".format(str(room_name), address[0], address[1], str(room_id), str(chatroom_join_id))) boradcast_message(room_id, "CHAT:{0}\nCLIENT_NAME:{1}\nMESSAGE:{2}".format(str(room_id), str(client_name), str(client_name) + " has joined this chatroom.\n\n")) elif (action_name == 'LEAVE_CHATROOM'): room_id = int(data[0].split(":")[1]) chatroom_join_id = int(data[1].split(":")[1]) client_name = data[2].split(":")[1] socket.sendall("LEFT_CHATROOM:{0}\nJOIN_ID:{1}\n".format(str(room_id), str(chatroom_join_id))) boradcast_message(room_id, "CHAT:{0}\nCLIENT_NAME:{1}\nMESSAGE:{2}\n\n".format(str(room_id), str(client_name), str(client_name) + " has left this chatroom.")) del rooms[room_id][chatroom_join_id] elif (action_name == 'DISCONNECT'): client_name = data[2].split(":")[1] chatroom_join_id = int(md5(client_name).hexdigest(), 16) for room_id in rooms.keys(): if chatroom_join_id in rooms[room_id]: boradcast_message(room_id, "CHAT:{0}\nCLIENT_NAME:{1}\nMESSAGE:{2}\n\n".format(str(room_id), str(client_name), str(client_name) + " has left this chatroom.")) if chatroom_join_id in rooms[room_id]: del rooms[room_id][chatroom_join_id] break
def telnet_process_options(self, socket, cmd, opt): IS = b'\00' # Inspired by # https://github.com/rapid7/metasploit-framework/blob/master/lib/msf/core/exploit/telnet.rb # https://github.com/jquast/x84/blob/cf3dff9be7280f424f6bcb0ea2fe13d16e7a5d97/x84/default/telnet.py if cmd == WILL and opt == ECHO: #hex:ff fb 01 name:IAC WILL ECHO description:(I will echo) socket.sendall(IAC + DO + opt) #hex(ff fd 01), name(IAC DO ECHO), descr(please use echo) elif cmd == DO and opt == TTYPE: #hex(ff fd 18), name(IAC DO TTYPE), descr(please send environment type) socket.sendall(IAC + WILL + TTYPE) #hex(ff fb 18), name(IAC WILL TTYPE), descr(Dont worry, i'll send environment type) elif cmd == SB: socket.sendall(IAC + SB + TTYPE + IS + self.env_term.encode() + IS + IAC + SE) # hex(ff fa 18 00 b"VT100" 00 ff f0) name(IAC SB TTYPE iS VT100 IS IAC SE) descr(Start subnegotiation, environment type is VT100, end negotation) elif cmd == SE: # server letting us know sub negotiation has ended pass # do nothing else: print("Unexpected telnet negotiation")
def handle_new_client(socket, address): global current_arctic_chars print('New connection from %s', address) arcticChar = ArcticChar(socket, address) socket.sendall( str(ArcticMessage("NOTIFY", "Welcome to FourSkulls.org(" + IP + ")"))) socket.sendall( str( ArcticMessage( "NOTIFY", "Current Chars connected are(" + ",".join(current_arctic_chars.keys()) + ")"))) socket.sendall(str(ArcticMessage("EXECUTE", "score"))) rfileobj = socket.makefile(mode='rb') try: while True: line = rfileobj.readline() if not line: print("client disconnected") break print("received %r" % line) (cmd, payload) = parse_message(line) if cmd == "CHARDATA": arcticChar.update(payload) # destroy the previous char if arcticChar.charData['@name'] in current_arctic_chars: previousArcticChar = current_arctic_chars[ arcticChar.charData['@name']] if previousArcticChar != arcticChar: previousArcticChar.kill() previousArcticChar.join() current_arctic_chars[arcticChar.charData['@name']] = arcticChar #socket.sendall(str(ArcticMessage("NOTIFY", "Received CharData: " + str(arcticChar.charData)))) print("FOUND CHARDATA for %s" % arcticChar.charData['@name']) arcticChar.start() else: temp_current_arctic_chars = current_arctic_chars.copy() if cmd != "NOTIFYALL" and cmd != "NOTIFY" and arcticChar.charData != None: del temp_current_arctic_chars[arcticChar.charData['@name']] commands[cmd].execute(payload, temp_current_arctic_chars) finally: rfileobj.close() print("CLOSING CONNECTION FOR %s" % str(arcticChar)) if arcticChar.charData != None and '@name' in arcticChar.charData: del current_arctic_chars[arcticChar.charData['@name']] arcticChar.kill() arcticChar.join()
def send_and_receive(self, socket, stream, save_cookies=False): res = [] i = socket.sendall(self.serialize()) if self.method == AjpForwardRequest.POST: return res r = AjpResponse.receive(stream) assert r.prefix_code == AjpResponse.SEND_HEADERS res.append(r) if save_cookies and 'Set-Cookie' in r.response_headers: self.headers['SC_REQ_COOKIE'] = r.response_headers['Set-Cookie'] # read body chunks and end response packets while True: r = AjpResponse.receive(stream) res.append(r) if r.prefix_code == AjpResponse.END_RESPONSE: break elif r.prefix_code == AjpResponse.SEND_BODY_CHUNK: continue else: raise NotImplementedError return res
def _uploadBytes(socket, duration_ms, packet_size, answer_with = None): """ Send byte arrays of size packet_size with end 0x00 until the duration_ms milliseconds have passed, then send a byte array with end 0xff :param socket: :param duration_ms: :param packet_size: :return: """ # if answer_with is specified, we wait for a request if answer_with: lines = "" while True: lines += str(socket.recv(1), "utf-8"); if lines.endswith("\r\n\r\n"): break; LOGGER.debug(lines) # send answer socket.sendall(bytes(answer_with,"utf-8")) timestamp_start = time.time() * 1000 sent_packets = 0 while (time.time() * 1000 - timestamp_start) < duration_ms: random_bytes = os.urandom(packet_size - 1) random_bytes += b'\x00' socket.sendall(random_bytes) sent_packets +=1 random_bytes = os.urandom(packet_size - 1) random_bytes += b'\xff' socket.sendall(random_bytes) sent_packets += 1 duration_up = time.time() * 1000 - timestamp_start return { "duration_ms" : int(duration_up), "bytes" : sent_packets * packet_size }
def enviar_archivo(socket, ip, rutaArchivo: str, hash, filesize, q: queue.Queue): # Agrega el objeto que se va a usar para hacer el log log_object = {"Cliente": ip} q.put(log_object) mensajeArchivo = "ARCHIVO:{0}:{1}".format( rutaArchivo.split(".")[-1], filesize) socket.sendall(mensajeArchivo.encode("utf-8")) data = socket.recv(1024) mensaje = data.decode("utf-8") if mensaje == "PREPARADO": log_object["Entregado"] = "No" with open(rutaArchivo, 'rb') as f: data = f.read(CHUNK_SIZE) start_ts = datetime.now().timestamp() while data: socket.sendall(data) data = f.read(CHUNK_SIZE) #Espera a recibir la confirmación de terminar data = socket.recv(1024) message = data.decode("utf-8") if message.startswith("RECIBIDO"): log_object["Entregado"] = "Si" end_ts = float(message.split(":")[-1]) final_time = (end_ts - start_ts) / 1000 socket.sendall("HASH:{}".format(hash).encode("utf-8")) socket.close() log_object["Tiempo"] = final_time else: print("El archivo no fue recibido")
def chat_run(socket): pid = os.fork() while 1: if not pid: #enfant envoi_plain = input("# => ") while ( envoi_plain ): # On est limité par notre n pour la taille des messages envoyés, on envoie donc notre message par blocs envoi_cypher = encrypt(envoi_plain[:64]) envoi_plain = envoi_plain[64:] envoi = envoi_cypher.to_bytes(512, byteorder='big', signed=False) socket.sendall(envoi) socket.sendall(config.ETX) # On envoie ETX (End Of Text) time.sleep(0.2) else: #parent recu = socket.recv(512) recu_plain = "" while (recu != config.ETX and recu != config.EOT): recu_cipher = int.from_bytes(recu, byteorder='big') recu_plain_part = decrypt(recu_cipher) recu_plain += recu_plain_part recu = socket.recv(512) if (recu_plain == 'quit' or recu_plain == 'exit'): socket.sendall( config.EOT) # On envoie EOT (End Of Transmission) os.kill(pid, 15) # terminaison du processus enfant break if (recu == config.EOT): os.kill(pid, 15) # terminaison du processus enfant break else: print('\r# <= ' + recu_plain + "\n# => ", end='') socket.close()
def send_string(socket, string): """ Sends a string to the getml engine (an actual string, not a bytestring). """ encoded = string.encode('utf-8') size = len(encoded) # By default, numeric data sent over the socket is big endian, # also referred to as network-byte-order! if sys.byteorder == 'little': socket.sendall( np.asarray([size]).astype(np.int32).byteswap().tostring()) else: socket.sendall(np.asarray([size]).astype(np.int32).tostring()) socket.sendall(encoded)
def app_thread(self, socket, address, ID): print("DEBUG: connected to app at {}:{}".format( address[0], address[1])) connected = True socket.sendall(self.make_packet("DATA", "CONNECTED")) while connected: recv = socket.recv(4096) print("DEBUG: ".format(recv)) if recv_msg.startswith("LOCK DOOR"): # $ get ready to lock door recv_msg, door_number = recv_msg.split('&') socket.sendall( self.make_packet("ACK", "LOCK DOOR&" + door_number)) """ add to queue? """ print("DEBUG: finished lock") elif recv_msg.startswith("UNLOCK DOOR"): # $ get ready to unlock door recv_msg, door_number = recv_msg.split('&') socket.sendall( self.make_packet("ACK", "UNLOCK DOOR&" + door_number)) """ add to queue? """ print("DEBUG: finished unlock") elif recv_msg == "SHUTTING DOWN": socket.close() connected = False
def sendMessage(socket, strMessage): #send the message in parameter socket.sendall(strMessage + "#")
def broadcast_to_all_clients(self, senders_socket): for client in self.clients_list: socket, (ip, port) = client if socket is not senders_socket: socket.sendall(self.last_received_message.encode('utf-8'))
def exec_and_fetch(socket, command): """docstring for exec_and_fetch""" socket.sendall(command) ret = socket.recv(1024) return ret
def reply(socket): for i in range(1, 6): string = "VM:" + str(i) + "\n" socket.sendall(string) time.sleep(2) socket.sendall("done:")