def run_client(server_address, server_port): # Ping a UDP pinger server running at the given address try: client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM) # Time out after 1 second client_socket.settimeout(1.0) print("Pinging", str(server_address), "on port", server_port) for i in range(10): client_socket.sendto("".encode(), (server_address, server_port)) try: time_start = time.time() _, _ = client_socket.recvfrom(1024) time_stop = time.time() except socket.timeout: print("Packet lost") else: print("RTT(Round trip time): {:.3f}ms".format((time_stop - time_start) * 1000)) finally: client_socket.close() return 0
def send_mail(sender_address, mail_server, receiver_address, message): try: client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM) # set a 1 second timeout client_socket.settimeout(1.0) # connect to mail server client_socket.connect((mail_server, 25)) def send(string): """Helper function: fix newlines, encode and send a string""" final = string.replace("\n", "\r\n").encode("ascii") print "Sending " + final + "..." client_socket.send(final) return 0 def recv_and_check(expected=250): """Helper function: recive reply and check it's ok""" reply = client_socket.recv(2048) print "Got: ", reply code = int(reply.rstrip().split()[0]) if code != expected: raise Exception(reply) return 0 # get initial message from server recv_and_check(220) # send greeting send("HELO {}\n".format(sender_address.split("@")[1])) recv_and_check() # set sender address send("MAIL FROM: {}\n".format(sender_address)) recv_and_check() # set receiver address send("RCPT TO: {}\n".format(receiver_address)) recv_and_check() # prepare to send message send("DATA\n") recv_and_check(354) # send the message itself followed by terminator send("{}\n.\n".format(message)) recv_and_check() send("QUIT\n") recv_and_check(221) finally: client_socket.close() return 0
def get_rtt(server_address, server_port): """Ping a UDP ping server running at the given address and show the ping status """ server = (server_address, server_port) message = bytes("", 'UTF-8') client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM) client_socket.settimeout(1.0) try: initial_time = current_milli_time() client_socket.sendto(message, server) client_socket.recvfrom(1024) final_time = current_milli_time() rtt = final_time - initial_time except: rtt = -1 client_socket.close() return rtt
def nl_socket_free(sock: socket.socket): """ close the socket """ try: sock.close() except AttributeError: # sock already closed pass return None
def CLIENT_HANDLER(CLIENT: socket.socket, ADDR): global TTL, SERVICE, WELCOME_BANNER, CONFIGS, COMMANDS, BROADCASTQUEUE_CLIENT, BROADCASTQUEUE_MESSAGE, SERVER_SOCKET ALIVE = True CONNECTED = True SEND_TEXTMSG(CLIENT, WELCOME_BANNER) while CONNECTED: CONFIG = RECIVE_TEXTMSG(CLIENT) if not CONFIG: ALIVE = False CONNECTED = CHECK_CONNECTION(CLIENT) else: ALIVE = True CONNECTED = False CONFIGS[CLIENT] = CONFIG BROADCASTQUEUE_CLIENT.append(SERVER_SOCKET) BROADCASTQUEUE_MESSAGE.append(f'{WELCOME_BANNER} {CONFIG[3:]}') try: CLOCK_START = time.perf_counter() while ALIVE and SERVICE: MESSAGE = RECIVE_TEXTMSG(CLIENT) if MESSAGE: CLOCK_START = time.perf_counter() print(ADDR, MESSAGE) if MESSAGE not in COMMANDS: BROADCASTQUEUE_CLIENT.append(CLIENT) BROADCASTQUEUE_MESSAGE.append(MESSAGE) elif MESSAGE == '!SHUTDOWN!': logger( 0, f'[SHUTDOWN] Client Side shutdown initated from {ADDR}' ) BROADCASTQUEUE_CLIENT.append(SERVER_SOCKET) BROADCASTQUEUE_MESSAGE.append( f'Server is being Shutdown by [{CONFIG[3:]}] please do !DISCONNECT! or \'exit\'' ) SERVICE = False ALIVE = False elif MESSAGE == '!DISCONNECT!': BROADCASTQUEUE_CLIENT.append(SERVER_SOCKET) BROADCASTQUEUE_MESSAGE.append(f'{CONFIG[3:]} has left ...') ALIVE = False elif MESSAGE == 'rUaLiVe?': SEND_TEXTMSG(CLIENT, 'True') else: CLOCK_END = time.perf_counter() - CLOCK_START if CLOCK_END > TTL: CHECK = CHECK_CONNECTION(CLIENT) if not CHECK: ALIVE = False else: CLOCK_START = time.perf_counter() else: pass except Exception as e: print(e) _ = input() finally: CLIENTS.remove(CLIENT) CLIENT.close() logger(0, f'[DISCONNECTION] Client {CONFIG[3:]} Disconnected ...')
def deal_client(self, client: socket.socket): message = MessageHandle() device_name = 'unknown' while True: # 接收数据 data = client.recv(1024) # 监听到数据发送过来 if data: # 把数据解析成字典 message.parsing = data # 只有当第一次解析数据的时候才把设备名更新 if 'ip' in message.parsing and device_name == 'unknown': device_name = message.parsing['ip'] message.save(device_name, message.parsing) self.client_hash_map[device_name] = client send_from_server = message.info_connect('server', '9999', 'data receive success!') message.encoding = (send_from_server, 'ascii') for each in self.client_hash_map: self.client_hash_map[each].send(message.encoding) print(message.encoding) # print(message.encoding) else: # 断开的时候删除设备名的键值对 self.client_hash_map.pop(device_name) client.close() break
def _echo_loop(self, connection: socket.socket) -> None: """ Get a connection and echo all the data received on it back (worker thread target). :param connection: Socket to communicate through with the client :return: None """ # Set socket to timeout to allow checking the alive flag connection.settimeout(0.1) # Loop for messages to send back while self.isAlive.isSet(): try: # Fail fast data = connection.recv(256) except socket.timeout: # No message available, retry if still alive continue except socket.error as e: # Different exception: Shutdown connection print(e) connection.close() else: if data: # Hook for resolving response echo_msg = self.determine_response(data) # Echo the message and wait for more if still alive connection.sendall(echo_msg) else: # Data is empty and there will be no future messages break # Shutdown connection properly connection.close()
def command_handler(soc: socket.socket, msg: str): print("command (" + msg + ") is handled by a thread") cmd = msg.split()[0] args = msg.split()[1:] # optlist, args = getopt.getopt(args, 'h', ['help']) # print(optlist, args) # TODO if cmd == "help" or msg == '\0' or cmd == "-h" or cmd == "--help": # commands.main_help(soc) # TODO more intelligent Help(soc) elif cmd == "stop-server": set_interaction(soc, False) os.kill(os.getpid(), signal.SIGINT) elif cmd == "ps": Ps(soc, args) elif cmd == "run": Run(soc, args) elif cmd == "rm": Rm(soc, args) elif cmd == "stop": Stop(soc, args) elif cmd == "images": Images(soc, args) else: # pass set_interaction(soc, False) send(soc, "pass", newline=True) soc.close() client_sockets.remove(soc)
def _close_connection(connection: socket.socket, dispose_of_connection: callable, mutex: threading.Lock): mutex.acquire() dispose_of_connection(connection) mutex.release() connection.close()
def run(self, bot_socket: socket.socket, bot_ip, bot_port, c2_server_ip, c2_server_port): from time import sleep server_socket = socket.create_connection( (c2_server_ip, c2_server_port), timeout=1) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.logger.info("Entering relay loop for bot {}:{}".format( bot_ip, bot_port)) self._run.set() while self._run.is_set(): bot_data = self.read(bot_socket) if bot_data: self.write(server_socket, bot_data) server_data = self.read(server_socket) if server_data: self.write(bot_socket, server_data) sleep(0.1) if bot_socket: bot_socket.close() if server_socket: server_socket.close()
def listen_to_client(self, clnt: socket.socket, addr: tuple) -> bool: """ Constantly running to listen for messages :param clnt: Client to listen for :param addr: Address of the client :return: ?? """ bytes_num = 1024 while True: try: # Message sent by client data = clnt.recv(bytes_num) if data: for client in self.clients: client.send(f"[{addr[0]}:{addr[1]}] - {data.decode()}". encode()) except: # Client disconnected print(f"Disconnected -> [{addr[0]}:{addr[1]}]") # Removes client from clients list self.clients.remove(clnt) clnt.close() # Sends disconnected message to all clients for client in self.clients: client.send( f"Disconnected -> [{addr[0]}:{addr[1]}]".encode()) return False
def start_work(self, conn: socket.socket, addr: Tuple[str, int]) -> None: if self.flags.threadless and \ self.threadless_client_queue and \ self.threadless_process: self.threadless_client_queue.send(addr) send_handle( self.threadless_client_queue, conn.fileno(), self.threadless_process.pid ) conn.close() else: work = self.work_klass( TcpClientConnection(conn, addr), flags=self.flags, event_queue=self.event_queue ) work_thread = threading.Thread(target=work.run) work_thread.daemon = True work.publish_event( event_name=eventNames.WORK_STARTED, event_payload={'fileno': conn.fileno(), 'addr': addr}, publisher_id=self.__class__.__name__ ) work_thread.start()
def split_stream(connection: socket.socket) -> Iterator[bytes]: """ Lowest level receiver which determines if received data is frame separator, which means previously received data should be yielded, or if received data is something else and receiver should continue to gather bytes. """ assert isinstance(connection, socket.socket) received_data = [] # type: ignore try: while True: next_bytes = connection.recv(RECEIVE_BYTES_PER_LOOP) if not next_bytes: raise socket.error() for next_byte in next_bytes: if bytes([next_byte]) == FRAME_SEPARATOR: data_to_yield = b''.join(received_data) received_data = [] if len(data_to_yield) <= MAXIMUM_FRAME_LENGTH: yield data_to_yield else: if MAXIMUM_FRAME_LENGTH < len(received_data): continue received_data.append(bytes([next_byte])) finally: connection.close()
def handle_client(self, connection: socket.socket): while True: client_msg = connection.recv(1024) connection.sendall(client_msg) if client_msg == None or client_msg.decode().lower() == "quit": break connection.close()
def receiver(self, login: str, client_sock: socket.socket): while self.running: try: data = client_sock.recv(1024) except ConnectionResetError: break if data == b'stop': print('Client {} stopped'.format(login)) self.connected.remove(client_sock) try: client_sock.sendall(b'') except ConnectionResetError: pass break decoded = data.decode() login, command = list(csv.reader(io.StringIO(decoded), delimiter=' ', quotechar='"'))[0] if command == 'create': self.players.append(login) print('Client {} {} sent: "{}"'.format(login, client_sock.getsockname(), decoded)) self.received_data.write_end(data) time.sleep(0.01) print('Stopped receiving from {} {}'.format(login, client_sock.getsockname())) client_sock.close()
def channel_thread(channel: socket.socket): host, port = channel.getpeername()[0:2] while True: size_buffer = channel.recv(1) if len(size_buffer) == 0: break size = size_buffer[0] print('(pending: {})'.format(size)) if size == 0: print('Closing connection to [{}]:{}'.format(host, port)) break buffer = bytes() while len(buffer) < size: buffer_size = min([size - len(buffer), 64]) buffer = buffer + channel.recv(buffer_size) print('Received message from [{}]:{}.'.format(host, port)) print(buffer.decode('utf-8')) channel.send(bytes([ size, ])) channel.send(buffer) send_john_cena(channel) channel.shutdown(socket.SHUT_WR) channel.close()
def loop(self, client_socket: socket.socket, address: Tuple[str, str]): """Main ioloop for reranking server results to the client""" server_socket = self.set_socket() session = self.get_session() prefix = 'Request (%s:%s): ' % address try: hooks.on_client_request(session, client_socket, self.search_path) self.logger.debug(prefix + 'search request.') if self.rerank: hooks.on_rerank_request(session) hooks.on_server_request(session) if self.rerank: hooks.on_rerank_response(session, self.model) if self.qa: hooks.on_qa(session, self.qa_model) if session.debug: hooks.on_debug(session) hooks.on_client_response(session, client_socket) except FrontendRequest: self.logger.info(prefix + 'frontend request') hooks.on_frontend_request(client_socket, session) except StatusRequest: self.logger.info(prefix + 'status request') hooks.on_status_request(client_socket, session, self.status) except UnknownRequest: path = session.get_request_path('url.path') self.logger.info(prefix + 'unknown path %s', path) hooks.on_unhandled_request(client_socket, server_socket, session) except MissingQuery: self.logger.warning(prefix + 'missing query') hooks.on_unhandled_request(client_socket, server_socket, session) except UpstreamServerError as exc: self.logger.error(prefix + 'server status %s' % exc) hooks.on_client_response(session, client_socket) except InvalidChoices as exc: self.logger.warning(prefix + '%s', exc.args) hooks.on_unhandled_request(client_socket, server_socket, session) except Exception as exc: # for misc errors, send back json error msg self.logger.error(prefix + str(exc), exc_info=True) hooks.on_proxy_error(client_socket, exc) finally: self.update_averages(**session.stats) client_socket.close() server_socket.close()
def tcp_connect_handler(sock: socket.socket, remote: list, server: socketserver.TCPServer): global dns_cache now = time.strftime("%Y-%m-%d %H:%M:%S") remote_addr = remote[0] if resolve_dns: if remote_addr not in dns_cache: remote_addr_info = [] try: remote_addr_info = socket.gethostbyaddr(remote_addr) except socket.herror: pass except: msg = "\n%s\n%s\n" % (sys.exc_info()[0], sys.exc_info()[1]) print(msg) if len(remote_addr_info) >= 1: remote_addr = remote_addr_info[0] dns_cache[remote[0]] = remote_addr else: remote_addr = dns_cache[remote_addr] print("[%s] Incoming connection on %s:%s from %s:%s" % (now, sock.getsockname()[0], sock.getsockname()[1], remote_addr, remote[1])) if fp_tcp_listen: fp_tcp_listen.write("%s,%s:%s,%s:%s\n" % (now, sock.getsockname()[0], sock.getsockname()[1], remote_addr, remote[1])) fp_tcp_listen.flush() sock.close()
def delete_client(self, client_name: str = "", client_idx: int = -1, sock: socket.socket = None): """Deletes a client. If a client has been given in parameters, then it will delete that client. Otherwise, it will delete the client that is currently selected in the client list widget.""" if (not client_name) and (client_idx == -1) and (not sock) and (self.client_list_widget.currentItem() is None): # handles for no clients existing. msg_box = QMessageBox(QMessageBox.Information, "Error", "You must select a client to delete.") msg_box.exec_() return elif (not client_name) and (client_idx == -1) and (not sock): # Here we handle if a user has clicked the delete button. # we handle by getting operating on the currently selected client in the client list client_widget_to_delete = self.client_list_widget.item(self.client_list_widget.currentRow()) client_name = client_widget_to_delete.text() client_idx = utils.get_client_idx(self, client_name) sock = self.all_sockets[client_idx] # here the client will be sending the 'END CONNECTION' message to the server. sock.send(bytes("END CONNECTION", "utf-8")) self.update_status(f"Closing and removing {client_name}'s socket...") sock.close() self.all_sockets.remove(sock) self.update_status(f"Removing {client_name} from list.") self.client_list_widget.takeItem(client_idx) self.update_status(f"Deleted client: {client_name}.") self.update_selected_client_idx()
def _disconnect_from_remote_server(self, sock: socket) -> None: if sock: try: self._logger.info("Disconnecting from remote host") sock.close() except Exception: pass
def workWithNode(s: socket.socket, address): global countNode global lockCount global lockLst try: #receive name dataRecv = s.recv(1024).decode() addNetworkIn(len(dataRecv)) try: if (dataRecv != ''): arg = parser.parse_args(dataRecv.lstrip().split(' ')) nameNode = arg.name[0] nameNode = str(address) + nameNode except socket.error: return lockLst.acquire() lstSock.append(s) lstName.append(nameNode) lockLst.release() #send coefficient, lower bound, epsilon dataSend = createMessage('', {'-h1': h1}) dataSend = createMessage(dataSend, {'-h2': h2}) dataSend = createMessage(dataSend, {'-h3': h3}) dataSend = createMessage(dataSend, {'-bound': valueKP1}) dataSend = createMessage(dataSend, {'-ses': session}) dataSend = createMessage( dataSend, {'-type': MyEnum.MonNode.SERVER_SET_ARG.value}) s.sendall(bytes(dataSend.encode('utf-8'))) addNetworkOut(len(dataSend)) #receive current value while 1: try: dataRecv = s.recv(1024).decode() addNetworkIn(len(dataRecv)) if (dataRecv != ''): arg = parser.parse_args(dataRecv.lstrip().split(' ')) nodeSession = arg.session[0] nodeValue = arg.value[0] if (nodeSession == session): updateTopK(nodeValue, nameNode, s) else: return except socket.error: return except socket.error: pass finally: s.close() removeInTop(nameNode, s) lockCount.acquire() countNode -= 1 lockCount.release()
def receive_file_stream_mode(client_socket:socket.socket, args): total_bytes_received = 0 total_messages_received = 0 file_name_size = client_socket.recv(4) file_name_size = struct.unpack('i', file_name_size)[0] file_name = client_socket.recv(file_name_size) file_name = file_name.decode("utf-8") print("start receiving {}".format(file_name)) with open(os.path.join(os.curdir,file_name),'wb')as f: while True: message = client_socket.recv(BLOCK_SIZE) if not message: break f.write(message) print("Received {} bytes".format(len(message))) total_messages_received += 1 total_bytes_received += len(message) # time.sleep(1) print("Done receiving file") client_socket.close() print("Protocol: {}".format(args.conn_type)) print("Total number of messages received: {}".format(total_messages_received)) print("Total number of bytes received: {}".format(total_bytes_received))
async def protocoled_fetch(self, client: socket.socket) -> tuple: # return None means close connection # return False means broken package try: async with timeouts(REQUEST_TIMEOUT): data_header = await self._loop.sock_recv(client, 4) except (ConnectionResetError, asyncio.TimeoutError): client.close() return None, None if not data_header: return None, None elif len(data_header) < 4: return False, None data_length = (data_header[0] << 16) + \ (data_header[1] << 8) + data_header[2] protocol = data_header[3] if protocol > 2: # reched protocal limit return None, None data = b'' try: async with timeouts(FOLLOWING_MESSAGE_TIMEOUT): while len(data) < data_length: data += await self._loop.sock_recv(client, data_length - len(data)) except (ConnectionResetError, asyncio.TimeoutError): client.close() return None, None return data, protocol
def readerJob(sock: socket): while True: try: headers = sock.recv(12) reqCode = int.from_bytes(headers[0:4], byteorder="little") bodyLen = int.from_bytes(headers[4:8], byteorder="little") print("收到数据, 数据代号: %d, 长度: %d" % (reqCode, bodyLen)) # addi = int.from_bytes(headers[8:12], byteorder=byteorder) if reqCode == 0: print("invalid reqCode 0, close & exit") sock.close() exit(-1) body = bytes() while len(body) < bodyLen: body += sock.recv(bodyLen - len(body)) if reqCode == CODE_CODE_DATA: bodyStr = str(body, encoding="utf-8") copy2clipboard(bodyStr) listbox.insert(1, strLogWithTime("收到了别人的代码,放到剪贴板了")) elif reqCode == CODE_SCRSHOT_DATA: ret = onScrShotGot(body) listbox.insert(1, strLogWithTime("收到了别人的截图,保存为%d.png了" % (ret))) else: pass except UnicodeEncodeError as e: print("编码错误(不要从微信电脑版复制代码) %s" % (e)) except Exception as e: print("connection closed, reader thread exit: %s" % (e)) return -1
def rec(self, sock: socket.socket, client): while not self.event.is_set(): try: data = sock.recv(1024) except Exception as e: logging.error(e) data = b'' print(data) if data.strip() == b'quit' or data.strip() == b'': with self.lock: self.clients.pop(client) sock.close() break msg = '{:%Y/%m/%d %H:%M:%S} [{}: {}] {}'.format( datetime.datetime.now(), *client, data.decode()) exp = [] exs = [] with self.lock: for c, s in self.clients.items(): try: s.send(msg.encode()) # 有可能出错 except: exp.append(c) exs.append(s) for c in exp: self.clients.pop(c) for s in exs: s.close()
def start_client(): # Client Setup # import needed libraries from socket import socket as Socket from socket import AF_INET, SOCK_STREAM HOSTNAME = 'localhost' # on same host PORTNUMBER = 12345 # same port number as server BUFFER = 1024 # size of the buffer SERVER = (HOSTNAME, PORTNUMBER) # create tuple of server address CLIENT2 = Socket(AF_INET, SOCK_STREAM) # create client socket CLIENT2.connect(SERVER) # connect client socket to server socket print(f'CLIENT2 >> Connected to SERVER over port {PORTNUMBER}.' ) # print verification string # loop until 'QUIT' is sent and received while True: MESSAGE2 = input( 'CLIENT2 >> Enter data you want to send or "QUIT" to exit-> ' ) # message to send to server CLIENT2.send(MESSAGE2.encode()) # send the encoded message to server REPLY2 = CLIENT2.recv(BUFFER).decode() # receive the servers reply print('SERVER >>', REPLY2) # print out the reply from server # break out of loop if QUIT is received if REPLY2 == 'QUIT': break print("CLIENT2 >> Closing Socket, GOODBYE." ) # print out break out of loop verification string CLIENT2.close() # close the socket
def client_serve(new_socket: socket.socket): print("=" * 50) rcv_content = new_socket.recv(1024).decode("utf-8") rcv_lines = rcv_content.splitlines() print(rcv_lines) # page = re.match(r"\s(\w+)(/(\w)+-(\w)+)*\.(\w){1,10}", rcv_lines[0]).group() page = re.match(r"[^/]+(/[^ ]*)", rcv_lines[0]).group(1) if page == "/": page = "/index.html" file_name = "./html" + page print(file_name) try: fp = open(file_name, "rb") except: send_content = "HTTP/1.1 200 OK\r\n" send_content += "\r\n" send_content += "----file not found----" new_socket.send(send_content.encode("utf-8")) else: html_content = fp.read() fp.close() send_content = "HTTP/1.1 200 OK\r\n" send_content += "\r\n" new_socket.send(send_content.encode("utf-8")) new_socket.send(html_content) new_socket.close()
def start_client(): # Client (Player) Setup # import needed libraries from socket import socket as Socket from socket import AF_INET, SOCK_STREAM HOSTNAME = 'localhost' # on same host PORTNUMBER = 11267 # same port number BUFFER = 80 # size of the buffer SERVER = (HOSTNAME, PORTNUMBER) PLAYER = Socket(AF_INET, SOCK_STREAM) PLAYER.connect(SERVER) print(f'PLAYER >> Connected to SERVER over port {PORTNUMBER}.') while True: GUESS = input('PLAYER >> Guess the password: '******'SERVER >>', ANSWER) if ANSWER == 'You chose wisely.': break PLAYER.close()
def handle_conn(self, conn: socket.socket, mask: int, data: Optional[bytes] = None) -> None: """ Handle an event on a connection socket. You can simulate an EVENT_READ on in-memory data by setting mask==0 and data!=None. """ assert self.sel pid = self.conns[conn] if mask & selectors.EVENT_READ: data = conn.recv(4096) # Messages are all one-byte codes for easy parsing. # The protocol is "any number of keepalive "k"s followed by a quit "q", so we can # safely ignore everything except the final byte of the message. if data: if data[-1:] == b"k": # keepalive message; leave the connection alone. return elif data[-1:] == b"q": # Graceful shutdown code. self.graceful_shutdowns.append(pid) else: raise ValueError("invalid message from pid_client:", data) # Error, EOF, or anything else. if self.listener is not None: raise det.errors.WorkerError("worker died before all workers connected") self.sel.unregister(conn) conn.close() del self.conns[conn]
def downloadFile(sock: socket.socket): request = recv(sock) if request["type"] == "download": filename = request["filename"] try: f = open(filename, "rb") except FileNotFoundError: send(sock, 0, 1, b"") else: success = 1 while True: send_data = f.read(MAXBYTES) if len(send_data) == MAXBYTES: #没到结尾 end = 0 send(sock, success, end, send_data) else: #到了结尾 end = 1 send(sock, success, end, send_data) f.close() sock.close() break else: raise Exception("发生了未知的错误,请求类型错误")
def transfer_from_tunnel(self, r_conn: socket_t, mask: int, buf: List[deque]) -> None: """receive data from tunnel and store in buffer""" w_conn = self.work_pool.inv.get(r_conn) if w_conn is None: self._sel.unregister(r_conn) r_conn.close() return data = b'' need_close = False try: data = r_conn.recv(BUF_SIZE) except ConnectionError: need_close = True if data == b'' or need_close: try: peer = r_conn.getpeername() logger.info( f'closing tunnel connection from {format_addr(peer)}' ) # noqa except OSError as e: logger.warn(e) self._sel.unregister(r_conn) r_conn.close() buf[NEG].append(sentinel) del self.work_pool.inv[r_conn] return buf[NEG].append(data)
def handle(conn: socket.socket, addr: tuple): """ Handler is the method that handles individual connections. It takes in the client socket, and the client address as input and Handles the connection to and fro from the server to the client """ thread_id = threading.get_ident() print('Thread {} recieved connection from {}'.format(thread_id, addr)) while True: # Read the query request = conn.recv(1024).decode('utf-8').strip('') print('Client said: {}'.format(request)) # If request asks to terminate break out of loop if request in ('', 'bye', 'exit'): break # Prepare response response = '' try: query_soln = eval(request) response = '[Thread {}] says: {}'.format(thread_id, query_soln) except Exception: response = '[Thread {}] says: {}'.format( thread_id, 'Bad query in request, please enter a valid expression') # Send response conn.sendall(response.encode('utf-8')) print('Responding with: {}'.format(response)) conn.sendall('bye'.encode('utf-8')) conn.close() return
def play_ping_pong(sock: socket.socket, request: Request): print("connection from: ", request.remote_ip) hit_id = int(request.query_string) if not (WEB_MIN <= hit_id <= WEB_MAX + 1): sock.sendall(b"HTTP/1.0 400 USER_ERROR\r\n\r\n") sock.close() return wss = WebSocketServer(sock=sock, request=request) observations = list() try: for i in range(201): time.sleep(0.1) msg = hex(random.randint(WEB_MIN, WEB_MAX)).encode() wss.send(msg, kind=TEXT) started = time.time() packets = wss.recvall() ended = time.time() if not len(packets) == 1: raise ConnectionAbortedError() delay = ended - started if packets[0] == msg: pass # print("good message in", delay) else: print("bad msg") raise ValueError() if i: # ignore first delay observations.append(delay) packed = struct.pack("d", delay) wss.send(packed, kind=BIN) finally: wss.close() print("%d observations for %s\n" % (len(observations), hex(hit_id))) if len(observations) > 2 and hit_id <= WEB_MAX: record_observations(hit_id, observations, request.headers.get("host"))
def main(): register_builtin_interface() server = Socket() if len(sys.argv) > 1: server_port = int(sys.argv[1]) else: server_port = DEFAULT_PORT print "Listening on port " + str(server_port) server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server.bind(("", server_port)) server.listen(50) Thread(target=process_event_queue).start() print "\nAutobus has successfully started up." try: while True: socket, address = server.accept() connection = Connection(socket, address) event_queue.put((connection.id, discard_args(connection.register)), block=True) connection.start() except KeyboardInterrupt: print "KeyboardInterrupt received, shutting down" event_queue.put((None, None), block=True) print "Event queue has been notified to shut down" except: print "Unexpected exception occurred in the main loop, shutting down. Stack trace:" print_exc() event_queue.put((None, None), block=True) print "Event queue has been notified to shut down" server.close()
def _recv(sock: socket.socket, size: int) -> bytes: """Secondary function to receive a specified amount of data.""" message = b'' while len(message) < size: packet = sock.recv(size - len(message)) if not packet: sock.close() raise OSError("Nothing else to read from socket") message += packet return message
def handlerequest(clientsocket: socket.socket): conn = connecttodb() cursor = conn.cursor() tagid = bytes.decode(clientsocket.recv(3)) query = 'select * from tagdata where id={0}'.format(tagid) cursor.execute(query) s=[] for (id, location, officehours, otherinfo, description) in cursor: s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description] s.insert(0, str(len(''.join(s)))+',') clientsocket.send(bytes(''.join(s),encoding='utf8')) clientsocket.close()
def __init__(self): # Set up the interrupt socket interrupt_server = Socket() interrupt_server.bind(("localhost", 0)) interrupt_server.listen(1) self.interrupt_writer = Socket() self.interrupt_writer.setblocking(False) self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1]) self.interrupt_reader = interrupt_server.accept() interrupt_server.shutdown(SHUT_RDWR) interrupt_server.close() self.interrupt_reader.setblocking(False) self.interrupt_writer.setblocking(False)
def _handle_connection(self, connection: socket.socket, address: Any) -> None: if self.ssl_options is not None: assert ssl, "Python 2.6+ and OpenSSL required for SSL" try: connection = ssl_wrap_socket( connection, self.ssl_options, server_side=True, do_handshake_on_connect=False, ) except ssl.SSLError as err: if err.args[0] == ssl.SSL_ERROR_EOF: return connection.close() else: raise except socket.error as err: # If the connection is closed immediately after it is created # (as in a port scan), we can get one of several errors. # wrap_socket makes an internal call to getpeername, # which may return either EINVAL (Mac OS X) or ENOTCONN # (Linux). If it returns ENOTCONN, this error is # silently swallowed by the ssl module, so we need to # catch another error later on (AttributeError in # SSLIOStream._do_ssl_handshake). # To test this behavior, try nmap with the -sT flag. # https://github.com/tornadoweb/tornado/pull/750 if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL): return connection.close() else: raise try: if self.ssl_options is not None: stream = SSLIOStream( connection, max_buffer_size=self.max_buffer_size, read_chunk_size=self.read_chunk_size, ) # type: IOStream else: stream = IOStream( connection, max_buffer_size=self.max_buffer_size, read_chunk_size=self.read_chunk_size, ) future = self.handle_stream(stream, address) if future is not None: IOLoop.current().add_future( gen.convert_yielded(future), lambda f: f.result() ) except Exception: app_log.error("Error in connection callback", exc_info=True)
def workWithUser(s : socket.socket): global parser global bUserConnect bUserConnect = True try: while 1: dataRecv = s.recv(1024).decode() if (dataRecv == ''): return except socket.error: return finally: bUserConnect = False s.close()
def client_socket_thread(address, client_socket: socket.socket, message_queue: queue.Queue, new_observer_queue_queue: queue.Queue, delete_observer_queue_queue: queue.Queue): next_state = '' tries = 0 if kicked == 1: kick = 0 #reset kicking status return else: nickname = address[0] + ':' + str(address[1]) #give them basic nickname of IP+port userlist.append(nickname) socketlist.append(client_socket) #add name to both socket list and user list observer_queue = queue.Queue() new_observer_queue_queue.put((client_socket, observer_queue)) client_sender(nickname, client_socket, message_queue, delete_observer_queue_queue) client_socket.close()
def run_server(server_port): # Run UDP pinger server try: server_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', server_port)) print("Ping server ready on port", server_port) while True: _, client_address = server_socket.recvfrom(1024) server_socket.sendto("".encode(), client_address) finally: server_socket.close() return 0
def call(self, *args, **kwargs): """ Remote call. """ socket = Socket(AF_INET, SOCK_STREAM) socket.connect(self.address) try: method = Document() method.name = self.name method.args = args method.kwargs = kwargs socket.send(method.dump()) reply = socket.recv(4096) result = Document() result.load(reply) return result finally: socket.close()
class SocketStream(Stream): def __init__(self, port): self.listener = Socket(AF_INET, SOCK_STREAM) self.listener.bind(('', port)) def open(self): self.listener.listen(1) self.socket, address = self.listener.accept() def read(self, size=1024): return self.socket.recv(size) def write(self, data): self.socket.sendall(data) def close(self): self.socket.close() self.listener.close()
def get_page(server_address, request_string): try: client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_address, REMOTE_PORT)) client_socket.send(request_string.encode()) reply = bytes() while True: part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore") # print part_body if not len(part_body): break reply += part_body finally: client_socket.close() return reply
def wait_connect(self): if self.needQuit: return self.init_graphic() self.informBoard = dashboard.InformBoard((10, 25), 15) test = 0 server = Socket(socket.AF_INET, socket.SOCK_STREAM) if not test: while 1: try: server.bind(("", config.Port)) break except socket.error as e: self.inform(str(e)) for event in pygame.event.get(): if event.type == QUIT: self.quit() break self.render_connection() sleep(1) server.listen(2) server.settimeout(0.0) player1 = Player(1, server) else: player1 = HumanPlayer(1) if self.add_human: player2 = HumanPlayer(2) # add handler for human player self.pyeventHandlers.append(player2) else: player2 = Player(2, server) players = [player1, player2, None] timer = pygame.time.Clock() # wait until connected 2 players finished = 0 player = players[finished] try: self.inform("waiting for AI to connect...") while finished < 2: for event in pygame.event.get(): if event.type == QUIT: self.quit() break if self.needQuit: break if player.connect(): self.add_player(player) self.inform("AI %s connected" % (player.name)) finished += 1 player = players[finished] self.render_connection() timer.tick(10) except KeyboardInterrupt: server.close() return False server.close() return True
import socket as Net from socket import socket as Socket import os,re,sys print Net.AF_INET,Net.SOCK_STREAM s = Socket(Net.AF_INET,Net.SOCK_STREAM) #get localhost name and ip address localhostName = Net.gethostname() localhostAddress = Net.gethostbyname(localhostName) print localhostName , localhostAddress try: s.bind((localhostAddress,10010)) print 'bind succeed!' s.listen(10) print 'start to listen!' except Exception as ex: print 'Error' , ex finally: s.close() print 'socket closed!'
class SixjetServer(Thread): """ A sixjet server. Server instances listen on both a specified port for native sixjet commands and on an Autobus 2 service. They are created with a function that will be used to write bytes to the parallel port; you'll typically pass an instance of parallel.Parallel's setData method, but any function accepting an integer will do. """ def __init__(self, write_function, port, bus, service_extra={}): """ Creates a new sixjet server. write_function is the function to use to write data to the parallel port. port is the port on which the native protocol listener should listen. service_extra is an optionally-empty set of values that will be added to the Autobus 2's service info dictionary. (Keys such as type will be added automatically, but such keys present in service_extra will override the ones added automatically.) bus is the Autobus bus to use. You can usually just use: from autobus2 import Bus with Bus() as bus: server = SixjetServer(..., bus, ...) ... and things will work. If write_function is None, a new parallel.Parallel instance will be created, and its setData method used. """ Thread.__init__(self) if write_function is None: import parallel self._parallel = parallel.Parallel() write_function = self._parallel.setData else: self._parallel = None # The event queue. Events can be pushed from any thread, but can only # be read and processed from the SixjetServer's run method. self.queue = Queue() # The list of remote native-protocol connections. This must only be # read and modified from the event thread. self.connections = [] # The current states of all of the jets. This must only be read and # modified from the event thread. self.jet_states = [False] * 16 # True to shut down the server. This shouldn't be modified; instead, # stop() should be called, which will post an event that sets this to # True. self.shut_down = False # The server socket listening on the native protocol port self.socket = Socket() self.socket.bind(("", port)) # The Autobus service we're publishing self.service = self.bus.create_service( {"type": "sixjet", "sixjet.native_port": port}, from_py_object=AutobusService(self)) def listen_for_connections(self): # We can just infinitely loop here as run() closes the socket after # the event loop quits, which will cause an exception to be thrown here while True: s = self.socket.accept() # The connection is just a dictionary for now. We're creating it # before so that we can partial it into the input thread. connection = Connection(self, s) self.post_event({"event": "connected", "connection": connection}) connection.start() def remote_message_received(self, connection, message): self.post_event({"event": "message", "message": message}) def run(self): # Start a socket listening for connections Thread(target=self.listen_for_connections).start() # Read events and process them in a loop. while not self.shut_down: # TODO: add support for scheduled tasks here, or use separate # threads to post events when they happen. The latter would offer # a better guarantee that events will be processed when they happen # due to Python's sleep-waiting whenever using get with a timeout # (which is due to attempting to wait on a condition with a timeout # doing the aforementioned). event = self.queue.get() try: self.handle_event(event) except: traceback.print_exc() finally: self.queue.task_done() with print_exceptions: self.socket.close() def stop(self): self.post_event({"event": "stop"}) def post_event(self, event): self.queue.put(event) def handle_event(self, event): if event["event"] == "message": self.handle_message(event["message"]) elif event["event"] == "stop": self.shut_down = True elif event["event"] == "connected": self.connections.append(event["connection"]) elif event["event"] == "disconnected": self.connections.remove(event["connection"]) else: print "Warning: unrecognized event type: %r" % event def handle_message(self, message): if message["command"] == "set": for n in message["on"]: self.jet_states[n] = True for n in message["off"]: self.jet_states[n] = False self.write_jets() elif message["command"] == "clear": for n in range(len(self.jet_states)): self.jet_states[n] = False self.write_jets() else: print "Invalid message: %r" % message def set_parallel_data(self, data): """ Sets the parallel port's data pins to the specified state, which should be a number from 0 to 255, then waits a bit. """ self.write_function(data) sleep(0.0032) # 3.2 milliseconds; increase if needed def write_jets(self): """ Writes the jet states stored in jet_states to the parallel port. """ # The sixjet board is basically made up of two 74HC595 8-bit shift # registers. For those not familiar with shift registers, they're basically # a queue of bits; new bits can be pushed in at one end, and when the queue # is full, old bits will be dropped from the other end. They can then be # instructed to take the bits currently in the queue and set 8 of their # pins to those values. They're perfect for controlling things like banks # of relays from the parallel port. # To push a bit into the queue, you set the shift register's DATA pin to # 0 if you want to push a 0 and 1 if you want to push a 1. Then you set the # CLOCK pin high and then back low. # To have the shift register take the bits in the queue and set its eight # output pins to their values, you set the shift register's STROBE pin high # and then low. # On the 74HC595 shift register, pin 11 is CLOCK, pin 12 is STORBE, and pin # 15 is DATA. Googling "74HC595 datasheet" will pull up a map of which pin # numbers are which physical pins on the 74HC595. # The sixjet board has two shift registers that each control a bank of 8 # relays. The module constants DATA_A and DATA_B correspond to the data # pins of each of these shift registers. CLOCK and STROBE are connected to # both shift registers' clock and strobe pins. # So, to write out the data... # Clear the parallel port self.set_parallel_data(0) # Iterate over all the jets in reverse order. We reverse the ordering here # since the first bit written out will end up shifted to the last position # in the shift register, so we want to write the last bit first. for a, b in reversed(zip(self.jet_states[0:8], self.jet_states[8:16])): # Set lines A and B to the jets we're writing values = (DATA_A if a else 0) | (DATA_B if b else 0) self.set_parallel_data(values) # Do it an extra time just to see if it helps some issues I've been # seeing with data occasionally getting clocked in wrong self.set_parallel_data(values) # Set clock high self.set_parallel_data(values | CLOCK) # Set clock low self.set_parallel_data(values) # Set strobe high self.set_parallel_data(STROBE) # Set strobe low self.set_parallel_data(0)
def tcp_connect_handler(sock:socket.socket, remote:list, server:socketserver.TCPServer): now = time.strftime("%Y-%m-%d %H:%M:%S") print("[%s] Incoming connection on %s:%s from %s:%s" % (now,sock.getsockname()[0],sock.getsockname()[1],remote[0],remote[1])) #sock.shutdown(socket.SHUT_RDWR) sock.close()