def __init__(self, address, port): self.address = address self.port = port self.seq = 0 self.session_id = random.randint(0, sys.maxint) self.socket = SocketClient(self.address, self.port) self.status = CubeStatus.UNKNOW
def __init__(self, HOST, PORT, music): super().__init__() self.username = str() self._run = True self._s = SocketClient(HOST, PORT) self._s.set_irc(self) self.music = music
def listen_fn(sock, clients, flags): """ Function to handle the socket server. Args: sock clients ssl_context flags Returns: None. """ while flags['is_running']: sub_addr = None sub_sock = None try: sub_sock, sub_addr = sock.accept() except Exception as ex: print( 'Server has exception when accept new connection: {}'. format(ex)) if sub_sock is not None: client = SocketClient(socket=sub_sock, last_active_ts=datetime.now(), flags={ 'is_running': True, 'is_recording': False, 'flush_num': 0, 'recording_start_ts': None }) # client.start() # start the sub thread handling the client clients.append(client) # save client to the `clients` list
def __init__(self): self.video_stream = VideoStream( src=0, usePiCamera=True, resolution=(640, 480), framerate=32).start() self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.1.223' self.port = 8486 time.sleep(2.0) self.timeCheck = time.time() self.socket_client = SocketClient()
def test_mock_500(self, set_up_mock_500): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) data, headers = self.get_info(sort='Apple') response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Server internal error'
def test_mock_timeout(self, set_up_mock_timeout): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) client.sock.settimeout(3.1) data, headers = self.get_info(sort='Apple') response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Server timed out'
def init(debug=False): global sock sock = SocketClient(timeout=1) global capture capture = CaptureThread(debug) capture.start() global markerDict markerDict = aruco.getPredefinedDictionary(aruco.DICT_4X4_250)
def test_mock_unavailable(self, set_up_without_mock): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) data = {'sort': 'Apple'} data = json.dumps(data) headers = self.get_headers(len(data.encode())) response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Connection refused'
def demo(): # Start Example TCP socket client for message in samplelist: # see samplelist in /data_streams/samples.py SocketClient(message=message).start() # Start HTTP example client HTTPClient().start() # Start Example Random Number Stream DataStream(random_nr_config, random_nr).start()
def init(clid): global client_socket global client_id client_socket = SocketClient(sc.ser_ip, sc.ser_port) # sign in recv_msg_1 = client_socket.send({"signal": "sign", "client_id": clid}) if recv_msg_1.get("client_id"): client_id = recv_msg_1.get("client_id") logging.info("client_id: %s" % client_id) else: sys.exit(recv_msg_1.get("erro")) logging.info("Line 44: client_id = %s" % client_id)
def experiment_code(experiment=None, time=None, logfile=None, offset=0): experiment_param = { 'experiment': experiment, #the experiment number determines the experiment type, with 'experiment_time': time, #this is the trial length 'logfile_name': logfile or 'Z:/Wilson Lab/Mel/FlyOnTheBall/data/data.hdf5', #this file will be saved in the experiment directory we choose in the GUI I believe, because of the matlab code 'logfile_auto_incr': True, 'logfile_auto_incr_format': '{0:06d}', 'logfile_dt': 0.01, 'offset': offset } client = SocketClient(experiment_param) client.run()
def __init__(self): # self.video_stream = VideoStream( # src=0, usePiCamera=True, width=640, height=480, framerate=32) self.video_stream = cv2.VideoCapture(0) self.video_stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.video_stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.43.52' self.port = 24485 time.sleep(2) self.timeCheck = time.time() self.socket_client = SocketClient() print("init success...")
def __init__(self, configuration, mark_processed, debug=False): """ Initialize the camera object. :param configuration: object containing parameters set by the user :param mark_processed: a method in moon_panorama_maker which marks tiles as processed :param debug: if True, the socket_client (FireCapture connection) is replaced with a mockup object with the same interface. It does not capture videos, but returns the acknowledgement as the real object does. """ QtCore.QThread.__init__(self) self.configuration = configuration # Register method in StartQT5 (module moon_panorama_maker) for marking tile as processed. self.mark_processed = mark_processed # The "triggered" flag is set to True in "workflow" to start an exposure. self.triggered = False # The "active" flag is looked up in "workflow" to find out if a video is being acquired. self.active = False self.terminate = False self.active_tile_number = -1 # Set the parameters for the socket connection to FireCapture. FireCapture might run on a # different computer. self.host = self.configuration.conf.get("Camera", "ip address") self.port = self.configuration.fire_capture_port_number # For debugging purposes, the connection to FireCapture can be replaced with a mockup class # which reads still images from files. These can be used to test the autoaligh mechanism. if debug: self.mysocket = SocketClientDebug( self.host, self.port, self.configuration.camera_debug_delay) if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera in debug mode, still camera emulated.") else: try: self.mysocket = SocketClient(self.host, self.port) except: raise CameraException( "Unable to establish socket connection to FireCapture, host: " + self.host + ", port: " + str(self.port) + ".") if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera: Connection to FireCapture program established.")
def run(self): # 引入爬虫模块 m = importlib.import_module(self.site_name) import pdb pdb.set_trace() seeds = Queue() if self.task_type == "spec_crawl_index": mc = settings.getMCInstance() db = mc['automotor_ershouche'] if self.site_name == "ganji_ershouche": cur = db['%s_city' % self.site_name].find({}, { 'url': 1, 'pinyin': 1, "name": 1 }) else: cur = db['%s_city' % self.site_name].find({}, { 'url': 1, "name": 1 }) for c in cur: seeds.put(c) import pdb pdb.set_trace() for x in range(self.thread_num): sock = SocketClient(host=self.server_ip, port=self.server_port, key=settings.tcp_login_key, user_name=self.name, logger=self.logger) crawler = m.Crawler(x, self.logger, self.task_type, self.proxy_type, sock, seeds, self.register, self.login) self.threads.append(gevent.spawn(crawler.run)) import pdb pdb.set_trace() gevent.joinall(self.threads)
async def on_client_message(message, host): client = SocketClient(host, int(os.getenv("CORE_PORT"))) client.write(message)
class HeartBeatClient(): server_status = pc.STATUS_RUNNING run_heartbeat = False client_id = -1 hb_period = 5 socket_client = SocketClient('localhost', '9900') def __init__(self): self.run_heartbeat = False def connect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send(json.dumps(register_request)) if self.client_id is None: raise IOError('Connection Failed') def disconnect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.UNREGISTER self.socket_client.send(json.dumps(register_request)) def start(self): try: t = threading.Thread(target=self.heartbeat, name=None) # set daemon so main thread can exit when receives ctrl-c t.setDaemon(True) t.start() except Exception as err: print("Error: unable to start thread", err) raise def heartbeat(self): skip_wait = False while self.run_heartbeat: if skip_wait is False: time.sleep(self.hb_period) else: skip_wait = False try: hb_request = {} hb_request[pc.MSG_TYPE] = pc.HEARTBEAT hb_request[pc.CLIENT_ID] = self.client_id hb_response_data = self.socket_client.send( json.dumps(hb_request)) # should be network error if hb_response_data is None: continue # print( 'Heart Beat response' + json.dumps(hb_response_data)) response = json.loads(hb_response_data) err = response.get(pc.ERROR) if err is not None: if err == pc.ERR_NOT_FOUND: register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( json.dumps(register_request)) # skip heartbeat period and send next heartbeat immediately skip_wait = True self.heartbeat() return return action = response.get(pc.ACTION_REQUIRED) if action is not None: action_request = {} if action == pc.PAUSE_REQUIRED: self.server_status = pc.PAUSED action_request[pc.MSG_TYPE] = pc.PAUSED elif action == pc.PAUSE_REQUIRED: self.server_status = pc.RESUMED action_request[pc.MSG_TYPE] = pc.RESUMED elif action == pc.SHUTDOWN_REQUIRED: self.server_status = pc.SHUTDOWN # stop heartbeat thread return action_request[pc.CLIENT_ID] = self.client_id self.socket_client.send(json.dumps(action_request)) else: self.server_status = response[pc.SERVER_STATUS] except socket.error as msg: print('Send Data Error. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) self.server_status = pc.STATUS_CONNECTION_LOST def get_target_items(self, type): hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id response = self.socket_client.send(json.dumps(hb_request)) return response[pc.DATA] def finish_target_items(self, type, items): hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id hb_request[pc.FINISHED_ITEMS] = json.dumps(items) self.socket_client.send(json.dumps(hb_request))
# create the Robot instance. robot = Robot() # initialize vision display vision_display = False if ENABLE_VISION_DISPLAY: vision_display = VisionDisplay(robot.getDisplay(VISION_DISPLAY_NAME), robot.getCamera('camera'), Display.RGB) # get the time step of the current world. Constants.TIMESTEP = int(robot.getBasicTimeStep()) # get the robot movement logic rbc = RobotControls(robot) # get the keyboard for user input kb = robot.getKeyboard() kb.enable(Constants.TIMESTEP) socket = False if ENABLE_SOCKET: socket = SocketClient('localhost', 4444) # configure Controller class to handle all logic (robot movement and user input) RobotController = RobotController(rbc, url="ws://localhost:3333", vision_display=vision_display, socket=socket) while robot.step(Constants.TIMESTEP) != -1: RobotController.Update()
def create_router_instance(self): SocketClient().create_socket_client_instance(self.interfaces) SocketServer().create_socket_server_instance(self.router_name)
from socket_client import SocketClient socket_client = SocketClient() socket_client.start("192.168.0.15", 65432)
class HeartBeatClient(object): server_status = pc.STATUS_RUNNING client_id = -1 hb_period = 5 skip_wait = False socket_client = SocketClient('192.168.1.105', 9000) def __init__(self): self.run_heartbeat = True def connect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( json.dumps(register_request)).decode() print('this is the client id :', self.client_id) if self.client_id is None: raise IOError('Connection Failed!') def disconnect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.socket_client.send(json.dumps(register_request)) def heartbeat(self): while self.run_heartbeat: if self.skip_wait is False: time.sleep(self.hb_period) else: self.skip_wait = False try: hb_request = {} hb_request[pc.MSG_TYPE] = pc.HEARTBEAT hb_request[pc.CLIENT_ID] = self.client_id hb_response_data = self.socket_client.send( json.dumps(hb_request)) # should be network error if hb_response_data is None: continue response = json.loads(hb_response_data) err = response.get(pc.ERROR) if err is not None: # client_id is not register if err == pc.ERR_NOT_FOUND: register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( register_request).decode() # skip heartbeat period and send next heartbeat immediately self.skip_wait = True self.heartbeat() return return action = response.get(pc.ACTION_REQUIRED) if action is not None: action_request = {} if action == pc.PAUSE_REQUIRED: action_request[pc.MSG_TYPE] = pc.PAUSED elif action == pc.RESUME_REQUIRED: action_request[pc.MSG_TYPE] = pc.RESUMED elif action == pc.SHUTDOWN_REQUIRED: # stop heartbeat thread return action_request[pc.CLIENT_ID] = self.client_id action_response = self.socket_client.send( json.dumps(action_request)) self.server_status = action_response.get(pc.SERVER_STATUS) else: # a normal heart beat self.server_status = response[pc.SERVER_STATUS] except socket.error as msg: print('Send Data Error. Error Code: ' + str(msg[0]) + 'Message' + msg[1]) self.server_status = pc.STATUS_CONNECTION_LOST def get_target_urls(self, type=pc.LOCATIONS): ''' :param type: pc.LOCATIONS or pc.TRIPLES ''' hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id response = self.socket_client.send(json.dumps(hb_request)) response = json.loads(response) crawl_delay = response.get(pc.CRAWL_DELAY) response_dict = {} if crawl_delay is not None: response_dict[pc.DATA] = response[pc.DATA] response_dict[pc.CRAWL_DELAY] = crawl_delay return response_dict else: response_dict[pc.DATA] = response[pc.DATA] return response_dict def finish_target_urls(self, items, _type=pc.FINISHED_ITEMS): ''' :param items: new url list ''' hb_request = {} hb_request[pc.MSG_TYPE] = _type hb_request[pc.CLIENT_ID] = self.client_id hb_request[pc.FINISHED_ITEMS] = items self.socket_client.send(json.dumps(hb_request))
def __init__(self): #Color initializations self.BLACK = (0, 0, 0) self.WHITE = (255, 255, 255) self.BALL_COLOR = (255, 255, 255) #Pygame initializations pygame.init() pygame.mixer.init(22050, -8, 16, 65536) self.size = (500, 500) self.screen = pygame.display.set_mode(self.size) self.clock = pygame.time.Clock() pygame.display.set_caption("PyPong") #Block position initializations self.left_y = self.size[1] / 2 self.right_y = self.size[1] / 2 self.pos_dict = {0: self.left_y, 1: self.right_y} self.block_size = 50 #Block movement booleans self.left_down = False self.right_down = False self.left_up = False self.right_up = False #Ball velocity variables self.ball_xv = 6 self.ball_yv = 6 self.ball_x = self.size[0] / 2 self.ball_y = self.size[1] / 2 self.abs_vel = 4 self.ball_time = 0 self.flip = 0 #Side Score Variables self.side_score = {0: 0, 1: 0} #Text Variables self.font = pygame.font.Font('freesansbold.ttf', 15) socket = SocketClient(self.pos_dict[1]) done = False self.ballInit() while not done: socket.pos = self.pos_dict[1] socket.send_msg() socket.recv_msg() self.pos_dict[0] = int(socket.pos_other) self.ball_x = socket.ball[0] self.ball_y = socket.ball[1] for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_s: self.left_down = True elif event.key == pygame.K_DOWN: self.right_down = True elif event.key == pygame.K_w: self.left_up = True elif event.key == pygame.K_UP: self.right_up = True elif event.type == pygame.KEYUP: if event.key == pygame.K_s: self.left_down = False elif event.key == pygame.K_DOWN: self.right_down = False elif event.key == pygame.K_w: self.left_up = False elif event.key == pygame.K_UP: self.right_up = False self.screen.fill(self.BLACK) self.checkMovement() self.drawBlocks() self.drawBall() self.checkColl() self.ballMove() self.clock.tick(120) pygame.display.flip() pygame.quit()
def __init__(self, host: str) -> None: addr, port = host.split(':') host = (addr, int(port)) self.sc = SocketClient(host)
def main(): """ main function """ app = QtWidgets.QApplication(sys.argv) main_window = QtWidgets.QMainWindow() qt_ui = Ui_SocketChat() qt_ui.setupUi(main_window) # j_settings = json.load('settings.json') j_settings = load_settings() if j_settings: password = j_settings['settings']['encryption'] host = j_settings['settings']['server'][0] port = int(j_settings['settings']['server'][1]) signals = Communicate() sck_client = SocketClient(server=(host, port), enc_pass=password, signals=signals) events = UI_Events(app, qt_ui, sck_client, main_window, j_settings) signals.signal_on_message.connect(events.on_message) signals.signal_on_pm_message.connect(events.on_pm_message) signals.signal_on_connect.connect(events.on_connect) signals.signal_on_disconnect.connect(events.on_disconnect) signals.signal_on_user_list.connect(events.on_user_list) signals.signal_clear_user_list.connect(events.on_clear_user_list) signals.signal_show_dialog_box.connect(events.show_dialog_box) qt_ui.btn_connect.clicked.connect(events.btn_connect_clicked) qt_ui.btn_disconnect.clicked.connect(events.btn_disconnect_clicked) qt_ui.actionConnect.triggered.connect(events.btn_connect_clicked) qt_ui.actionDisconnect.triggered.connect(events.btn_disconnect_clicked) qt_ui.actionClose.triggered.connect(events.on_close) qt_ui.btn_send.clicked.connect(events.btn_send_clicked) qt_ui.txt_message.returnPressed.connect(events.txt_message_enter) qt_ui.txt_username.returnPressed.connect(events.txt_username_enter) qt_ui.lst_users.doubleClicked.connect(events.lst_users_double_clicked) qt_ui.actionPrerefences.triggered.connect(events.open_preferences) qt_ui.btn_disconnect.setVisible(False) qt_ui.actionDisconnect.setVisible(False) qt_ui.lbl_sbar_conn.setStyleSheet('color: red') qt_ui.lbl_sbar_conn.setText('Disconnected') qt_ui.lbl_sbar_login.setText('') qt_ui.lbl_sbar_user_count.setText('0') qt_ui.statusbar.addPermanentWidget(qt_ui.lbl_sbar_conn, 2) qt_ui.statusbar.addPermanentWidget(qt_ui.lbl_sbar_login, 3) qt_ui.statusbar.addPermanentWidget(qt_ui.lbl_sbar_user_count, 7) qt_ui.txt_message.setReadOnly(True) ############################# SYSTEM TRAY ICON ############################# icon = QIcon() icon.addPixmap(QPixmap(":/images/resources/images/chat_48x48.ico"), QIcon.Normal, QIcon.Off) main_window.tray_icon = QSystemTrayIcon(main_window) main_window.tray_icon.setIcon(icon) main_window.tray_icon.activated.connect(events.sys_tray_icon_activated) # main_window.tray_icon.messageClicked.connect(main_window.show) show_action = QAction("Show", main_window) quit_action = QAction("Exit", main_window) hide_action = QAction("Hide", main_window) show_action.triggered.connect(main_window.show) hide_action.triggered.connect(main_window.hide) quit_action.triggered.connect(events.appQuitEvent) tray_menu = QMenu() tray_menu.addAction(show_action) tray_menu.addAction(hide_action) tray_menu.addAction(quit_action) main_window.tray_icon.setContextMenu(tray_menu) main_window.tray_icon.show() ########################################3################################### main_window.closeEvent = events.closeEvent main_window.show() sys.exit(app.exec_())
if __name__ == "__main__": from socket_client import SocketClient, SocketClientDebug app = QtWidgets.QApplication(sys.argv) c = configuration.Configuration() tel = telescope.Telescope(c) host = 'localhost' port = c.fire_capture_port_number if c.camera_debug: mysocket = SocketClientDebug(host, port, c.camera_debug_delay) else: try: mysocket = SocketClient(host, port) except: print( "Camera: Connection to FireCapture failed, expect exception.") exit() # date_time = '2015/05/18 15:20:30' date_time = datetime(2015, 10, 26, 21, 55, 00) # date_time = datetime.now() me = moon_ephem.MoonEphem(c, date_time, debug=c.ephemeris_debug) al = Alignment(c, debug=c.alignment_debug) al.set_telescope(tel) al.set_moon_ephem(me)
def set_up(run): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) return client
from server_auth import ServerAuth from socket_client import SocketClient key = "randomstuff12345" raw_text = "raffles|31|5|7|9" auth = ServerAuth() # cipher_text = auth.encrypt_text(raw_text, key) # print(cipher_text) # # decoded_text = auth.decrypt_text(cipher_text, key) # print(decoded_text) socket_client = SocketClient('localhost', 8888) socket_client.connect() # Final_eval_server command: # python final_eval_server_5moves.py localhost 8888 group_num_123 user_inp = '' while 1: print('Input: ') user_inp = input() try: if user_inp == '1': # msg = auth.encrypt_text(raw_text, key) socket_client.send(raw_text) print('sent') print()
def __init__(self, window): threading.Thread.__init__(self) self.done = False self.window = window self.socket = None self.socket = SocketClient('localhost', 10000, self.window.set_status)
def create_new_client(self, rower_index): self.clients.append(SocketClient(rower_index))
#dir_name = 'mfw/' # db manager webdrivers = {} dbmanager = MongoRedisUrlManager() is_root_page = True threads = [] options = webdriver.ChromeOptions() # 设置中文 options.add_argument('lang=zh_CN.UTF-8') prefs = {"profile.managed_default_content_settings.images": 2} options.add_experimental_option("prefs", prefs) # use hdfs to save pages # hdfs_client = InsecureClient('http://54.223.92.169:50070', user='******') socket_client = SocketClient('localhost', 20012) client_id = 0 hb_period = 5 run_heartbeat = True server_status = pc.STATUS_RUNNING init() start_heart_beat_thread() crawl() finish() for dr in webdrivers: dr.close() dr.quit()
from socket_client import SocketClient socket_client = SocketClient(socket_numbers=2) socket_client.add_socket({ "host": "192.168.1.163", "port": 12345 }).add_socket({ "host": "192.168.1.211", "port": 12345 }) socket_client.start()