def __init__(self, base_url): self.base_url = base_url self.sio = socketio.Client() self.uuid = str(uuid.uuid4()) self.namespace = '/rowma'
import json import requests import socketio asset = {'name': 'carrying_asset'} carried_agent = {'name': 'carried_agent'} waits = [] responses = [] carrying_socket = socketio.Client() carried_socket = socketio.Client() token = None carried_token = None def connect_actors(): global token, carried_token response = requests.post('http://127.0.0.1:12345/connect_asset', json=json.dumps(asset)).json() token = response['message'] requests.post('http://127.0.0.1:12345/register_asset', json=json.dumps({'token': token})) carrying_socket.emit('connect_registered_asset', data=json.dumps({'token': token})) carried_response = requests.post('http://127.0.0.1:12345/connect_agent', json=json.dumps(carried_agent)).json() carried_token = carried_response['message'] requests.post('http://127.0.0.1:12345/register_agent',
import socketio as socket import random import math import copy # REFERENCIA # http://dhconnelly.com/paip-python/docs/paip/othello.html#section-14 # https://inventwithpython.com/chapter15.html socketIO = socket.Client() url = 'localhost:4000' userName = '******' tournament_id = '12' N: int = 8 def validarMovimientos(board, jugadorID, x, y): global N index = x * N + y voltear = [] index_voltear = [] around = [[1, -1], [0, -1], [0, 1], [1, 1], [1, 0], [-1, 0], [-1, -1], [-1, 1]] if board[index] != 0 or not posicion_valida(x, y): return False, voltear, None testboard = copy.deepcopy(board) testboard[index] = jugadorID oponent_turn_id = 1 if jugadorID == 1:
def start_connection(self): self.sio = socketio.Client() self.sio.connect("http://10.30.117.159:5000") @self.sio.on("system") def on_connect(data): self.takeMessage(data["message"] + "\n", data["room"], "system") @self.sio.on("msg") def on_connect(data): self.takeMessage(data["name"] + "\n" * 2 + data["message"] + "\n", data["room"]) @self.sio.on("currentuser") def on_connect(data): for ID in data: if data[ID]: self.friendList.friendBox.findItems( self.friend[ID], Qt.MatchExactly)[0].setBackground( QColor(0, 255, 0, 70)) else: self.friendList.friendBox.findItems( self.friend[ID], Qt.MatchExactly)[0].setBackground( QColor(126, 134, 150, 70)) @self.sio.on("exist") def on_connect(data): self.currentFriendCheck = data["boolean"] self.currentFriendName = data["name"] self.currentFriend = data["id"] @self.sio.on("checkinout") def on_connect(data): if data["id"] == self.id or not data["id"] in list(self.friend): return if data["type"] == "in": self.friendList.friendBox.findItems( self.friend[data["id"]], Qt.MatchExactly)[0].setBackground(QColor(0, 255, 0, 70)) else: self.friendList.friendBox.findItems( self.friend[data["id"]], Qt.MatchExactly)[0].setBackground( QColor(126, 134, 150, 70)) @self.sio.on("invite") def on_connect(data): # roomName = "&&".join(sorted([self.id, data["friendid"]])) # newChat = Chat() # newChat.sendButton.clicked.connect(lambda : self.sendMessage(roomName=roomName)) # self.chatting[roomName] = newChat # self.userInOut(room=roomName) # self.roomList.roomBox.addItem(roomName) pass @self.sio.on("roomclient") def on_connect(data): self.chatting[data["room"]].currentFriendBox.clear() for client in data["clients"]: item = QListWidgetItem() icon = self.friendList.userCircleIcon item.setIcon(icon) item.setText(client) item.setFont(QFont("Arial", 16)) self.chatting[data["room"]].currentFriendBox.addItem(item) self.friendList.friendButton.clicked.connect(self.menuButtonClicked) self.friendList.chattingButton.clicked.connect(self.menuButtonClicked) self.friendList.friendMakeButton.clicked.connect( self.friendButtonClicked) self.friendList.friendDelButton.clicked.connect( self.friendButtonClicked) self.friendList.friendDelOkButton.clicked.connect( self.friendButtonClicked) self.friendList.friendDelCancelButton.clicked.connect( self.friendButtonClicked) self.roomList.friendButton.clicked.connect(self.menuButtonClicked) self.roomList.chattingButton.clicked.connect(self.menuButtonClicked) self.roomList.makeRoomButton.clicked.connect( self.makeRoomButtonClicked) self.roomList.deleteRoomButton.clicked.connect( self.deleteRoomButtonClicked) self.roomList.checkRoomButton.clicked.connect( self.checkRoomButtonClicked) self.roomList.cancelRoomButton.clicked.connect( self.cancelRoomButtonClicked) self.roomList.roomBox.itemDoubleClicked.connect(self.openChatting) self.makeFriend.friendSearchButton.clicked.connect( self.makeFriendButtonClicked) self.makeFriend.okButton.clicked.connect(self.makeFriendButtonClicked) self.makeFriend.cancelButton.clicked.connect( self.makeFriendButtonClicked) self.makeFriend.backButton.clicked.connect( self.makeFriendButtonClicked) self.security.verifyButton.clicked.connect(self.securityCheck) self.userInit.okButton.clicked.connect(self.dataReadingException) self.friendList.friendBox.itemDoubleClicked.connect( self.friendListClicked)
""" GeoRide socket-io implementation """ import logging import socketio from georideapilib.api import GEORIDE_API_HOST _LOGGER = logging.getLogger(__name__) sio = socketio.Client(reconnection=True) # pylint: disable=C0103 @sio.on('connect') def on_connect(): """ event: connected """ _LOGGER.debug('GeoRide socket connected') @sio.on('disconnect') def on_disconnect(): """ event: disconnected """ _LOGGER.debug('GeoRide socket disconnected') class GeoRideSocket(): """docstring for GeoRideSocket""" def __init__(self): self._on_message_callback = None self._on_device_callback = None self._on_position_callback = None self._on_alarm_callback = None self._on_refresh_tracker_callback = None
start_system_path = root + '/start_system.py' base_url = '192.168.1.110' api_port = 12345 sim_port = 8910 secret = 'temp' connect_agent_url = f'http://{base_url}:{api_port}/connect_agent' connect_monitor_url = f'http://{base_url}:{api_port}/connect_monitor' sim_command = [ 'python3', start_system_path, *f'-conf {root+temp_config} -pyv 3 -g True -url {base_url} -secret {secret} -first_t 20' .split(' ') ] exp_name = 'PACKAGE_SIZE_API' agent_socket = socketio.Client() monitor_socket = socketio.Client() agent_token = None monitor_token = None agent_package_sizes = [] monitor_package_sizes = [] process_finished = False experiments = [100, 100] current_prob = None @monitor_socket.on('percepts') def percepts(msg): global monitor_package_sizes #
import json import requests import socketio delivering_agent = {'name': 'delivering_agent'} receiving_agent = {'name': 'receiving_agent'} delivering_socket = socketio.Client() receiving_socket = socketio.Client() waits = [] responses = [] delivering_token = None receiving_token = None delivery_location = None water_loc = None collected = False deliver_request = False def connect_actors(): global delivering_token, receiving_token response = requests.post('http://127.0.0.1:12345/connect_agent', json=delivering_agent).json() delivering_token = response['message'] delivering_socket.emit('register_agent', data={'token': delivering_token}) response = requests.post('http://127.0.0.1:12345/connect_agent',
from environment.card import get_card_count, get_card_color, get_card_shape, Card, CardSelection from environment.agent import Agent from environment.position import Position, v3_pos_to_position from environment.terrain import Terrain from environment.util import interpret_card_info, construct_object from simulation.util import HEX_WIDTH, HEX_DEPTH from model.modules.trajectory_distribution import normalize_trajectory_distribution from environment.terrain import cell_name_to_terrain from environment.position import v3_pos_to_position from model.modules.auxiliary import Auxiliary from environment.environment_objects import ObjectType from learning.inference import load_vocabulary from simulation.python_game import PythonGame from model.model_wrappers.model_creator import get_model_wrapper SOCKET = socketio.Client() #MODEL_DIR = 'agent_learning/experiments/finetune_aggregate_0.7_1' #SAVE_NAME = 'model_17_score.pt' MODEL_DIR = 'agent_learning/experiments/finetune_aggregate_0.7_0' SAVE_NAME = 'model_13_score.pt' def get_current_time(): # Stores the current time and date (including microseconds) return datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') class GameArgs: def __init__(self):
def __init__(self): self.sio = socketio.Client() self.sio.connect('http://localhost:3000') self.connection = http.client.HTTPConnection('localhost:3000') self.headers = {'Content-type': 'application/json'}
def test_emit_permissions(self): r = requests.post(self.url + "/token", data={ 'email': 'a', 'password': '******' }) response1 = json.loads(r.text) r = requests.post(self.url + "/token", data={ 'email': 'b', 'password': '******' }) response2 = json.loads(r.text) r = requests.post(self.url + "/token", data={ 'email': 'c', 'password': '******' }) response3 = json.loads(r.text) def handle_chat_message(sno, message): self.chat_messages_counter[sno - 1] += 1 sio1 = socketio.Client() sio2 = socketio.Client() sio3 = socketio.Client() self.sockets.append(sio1) self.sockets.append(sio2) self.sockets.append(sio3) sio1.on('chat-message-client', handler=partial(handle_chat_message, 1)) sio2.on('chat-message-client', handler=partial(handle_chat_message, 2)) sio3.on('chat-message-client', handler=partial(handle_chat_message, 3)) sio1.connect(self.url) sio2.connect(self.url) sio3.connect(self.url) sio1.emit('start', response1) sio2.emit('start', response2) sio3.emit('start', response3) QtTest.QTest.qWait(100) sio1.emit( 'chat-message', { "p_id": 1, "token": response1['token'], "message_text": "message from 1", "reply_id": -1 }) sio3.emit( 'chat-message', { "p_id": 1, "token": response3['token'], "message_text": "message from 3 - 1", "reply_id": -1 }) sio3.emit( 'chat-message', { "p_id": 3, "token": response3['token'], "message_text": "message from 3 - 2", "reply_id": -1 }) sio1.sleep(1) sio2.sleep(1) sio3.sleep(1) assert self.chat_messages_counter[0] == 2 assert self.chat_messages_counter[1] == 1 assert self.chat_messages_counter[2] == 2
def socket(self): sio = socketio.Client() @sio.event def connect(): print("connection established") ready_data = {"listId": self.list_id} sio.emit("readyForMatch", json.dumps(ready_data)) @sio.event def log(data): log_data = json.loads(data) if log_data is None: return if "log" not in log_data: return logs = log_data["log"] logs.reverse() if self.event_callback is None: return if len(logs) > 1: return event_string = None for events in logs: for event, event_data in events.items(): if event == self.EVENT_KILL: event_string = "{} ({}) 🔫{} {} ({}) with {}".format( event_data["killerName"], event_data["killerSide"], "💀" if event_data["headShot"] else "", event_data["victimName"], event_data["victimSide"], event_data["weapon"], ) elif event == self.EVENT_ROUND_END: event_string = "Round over, {} wins. Current score: CT {} - T {}".format( event_data["winner"], event_data["counterTerroristScore"], event_data["terroristScore"], ) else: print("Uncaught event: {!s}".format(event)) print(event_data) # Send the event string to callback function if event_string is not None: self.event_callback(event_string) @sio.event def scoreboard(data): players = { self.TEAM_COUNTER_TERRORIST: [], self.TEAM_TERRORIST: [], } for team in [self.TEAM_COUNTER_TERRORIST, self.TEAM_TERRORIST]: for player in data[team]: players[team].append( Player( adr=player["damagePrRound"], alive=player["alive"], assists=player["assists"], deaths=player["deaths"], has_defusekit=player["hasDefusekit"], helmet=player["helmet"], hltv_id=player["dbId"], hp=player["hp"], kevlar=player["kevlar"], money=player["money"], name=player["name"], nick=player["nick"], primary_weapon=player.get("primaryWeapon", None), score=player["score"], steam_id=player["steamId"], )) team_terrorist = Team( team_id=data["tTeamId"], name=data["terroristTeamName"], score=data["tTeamScore"], players=players[self.TEAM_TERRORIST], ) team_counter_terrorist = Team( team_id=data["ctTeamId"], name=data["ctTeamName"], score=data["ctTeamScore"], players=players[self.TEAM_COUNTER_TERRORIST], ) scoreboard = Scoreboard( map_name=data["mapName"], bomb_planted=data["bombPlanted"], current_round=data["currentRound"], terrorists=team_terrorist, counter_terrorists=team_counter_terrorist, ) if self.sb_callback is not None: self.sb_callback(scoreboard) @sio.event def disconnect(): print("disconnected from server") # Connect to the scorebot URI. sio.connect("https://scorebot-secure.hltv.org") return sio
class ConciergeBot: sio = socketio.Client(logger=True) tasks = dict() def __init__(self, token, user, host, port): """This bot lists users joining a designated waiting room and sends a group of users to a task room as soon as the minimal number of users needed for the task is reached. :param token: A uuid; a string following the same pattern as `0c45b30f-d049-43d1-b80d-e3c3a3ca22a0` :type token: str :param user: ID of a `User` object that was created with the token. :type user: int :param host: Full URL including protocol and hostname. :type host: str :param port: Port used by the slurk chat server. :type port: int """ self.token = token self.user = user self.uri = host if port is not None: self.uri += f":{port}" self.uri += "/slurk/api" LOG.info( f"Running concierge bot on {self.uri} with token {self.token}") # register all event handlers self.register_callbacks() def run(self): # establish a connection to the server self.sio.connect( self.uri, headers={ "Authorization": f"Bearer {self.token}", "user": self.user }, namespaces="/", ) # wait until the connection with the server ends self.sio.wait() def register_callbacks(self): @self.sio.event def status(data): if data["type"] == "join": user = data["user"] task = self.get_user_task(user) if task: self.user_task_join(user, task, data["room"]) elif data["type"] == "leave": user = data["user"] task = self.get_user_task(user) if task: self.user_task_leave(user, task) @staticmethod def message_callback(success, error_msg=None): """Is passed as an optional argument to a server emit. Will be invoked after the server has processed the event, any values returned by the event handler will be passed as arguments. :param success: `True` if the message was successfully sent, else `False`. :type success: bool :param error_msg: Reason for an insuccessful message transmission. Defaults to None. :type status: str, optional """ if not success: LOG.error(f"Could not send message: {error_msg}") exit(1) LOG.debug("Sent message successfully.") def get_user_task(self, user): """Retrieve task assigned to user. :param user: Holds keys `id` and `name`. :type user: dict """ task = requests.get(f'{self.uri}/users/{user["id"]}/task', headers={"Authorization": f"Bearer {self.token}"}) if not task.ok: LOG.error(f"Could not get task: {task.status_code}") exit(2) LOG.debug("Got user task successfully.") return task.json() def create_room(self, layout_id): """Create room for the task. :param layout_id: Unique key of layout object. :type layout_id: int """ room = requests.post(f"{self.uri}/rooms", headers={"Authorization": f"Bearer {self.token}"}, json={"layout_id": layout_id}) if not room.ok: LOG.error(f"Could not create task room: {room.status_code}") exit(3) LOG.debug("Created room successfully.") return room.json() def join_room(self, user_id, room_id): """Let user join task room. :param user_id: Identifier of user. :type user_id: int :param room_id: Identifier of room. :type room_id: int """ response = requests.post( f"{self.uri}/users/{user_id}/rooms/{room_id}", headers={"Authorization": f"Bearer {self.token}"}) if not response.ok: LOG.error(f"Could not let user join room: {response.status_code}") exit(4) LOG.debug("Sending user to new room was successful.") return response.headers["ETag"] def delete_room(self, user_id, room_id, etag): """Remove user from (waiting) room. :param user_id: Identifier of user. :type user_id: int :param room_id: Identifier of room. :type room_id: int :param etag: Used for request validation. :type etag: str """ response = requests.delete( f"{self.uri}/users/{user_id}/rooms/{room_id}", headers={ "Authorization": f"Bearer {self.token}", "If-Match": etag }) if not response.ok: LOG.error( f"Could not remove user from room: {response.status_code}") exit(5) LOG.debug("Removing user from room was successful.") def user_task_join(self, user, task, room): """A connected user and their task are registered. Once the final user necessary to start a task has entered, all users for the task are moved to a dynamically created task room. :param user: Holds keys `id` and `name`. :type user: dict :param task: Holds keys `date_created`, `date_modified`, `id`, `layout_id`, `name` and `num_users`. :type task: dict :param room: Identifier of a room that the user joined. :type room: str """ task_id = task["id"] user_id = user["id"] user_name = user["name"] # register task together with the user_id self.tasks.setdefault(task_id, {})[user_id] = room if len(self.tasks[task_id]) == task["num_users"]: new_room = self.create_room(task["layout_id"]) # list cast necessary because the dictionary is actively altered # due to parallely received "leave" events for user_id, old_room_id in list(self.tasks[task_id].items()): etag = self.join_room(user_id, new_room["id"]) self.delete_room(user_id, old_room_id, etag) del self.tasks[task_id] self.sio.emit("room_created", { "room": new_room["id"], "task": task_id }) else: self.sio.emit("text", { "message": f"### Hello, {user_name}!\n\n" "I am looking for a partner for you, it might take " "some time, so be patient, please...", "receiver_id": user_id, "room": room, "html": True }, callback=self.message_callback) def user_task_leave(self, user, task): """The task entry of a disconnected user is removed. :param user: Holds keys `id` and `name`. :type user: dict :param task: Holds keys `date_created`, `date_modified`, `id`, `layout_id`, `name` and `num_users`. :type task: dict """ task_id = task["id"] user_id = user["id"] if task_id in self.tasks and user_id in self.tasks[task_id]: del self.tasks[task["id"]][user["id"]]
def __init__(self, app): self.App = app self.Client = socketio.Client(reconnection=True) self.init_handlers() self.Thread = Thread(target=self.connect).start()
def __init__(self): self.sioc = socketio.Client()
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import os from os import system, name as so_name import requests import logging # remove log from socket io logging.basicConfig(filename=os.devnull, filemode='w') if (True): import socketio APP_URL = 'https://twitter-watcher-backend.herokuapp.com' # socket io sio = socketio.Client(logger=False, engineio_logger=False) # create predictor predicted = [] predictor = SentimentIntensityAnalyzer() def remove_hashtags(text): out = "" words = str(text).split(' ') for word in words: if ("@" not in word and "https://" not in word and not ("&" in word and ";" in word)): out += word.replace('#', '') + " " return out.strip()
def daemon(self, foreground=False): import socketio if not foreground: # Hide console if we're on Windows if os.name == 'nt': import ctypes ctypes.windll.user32.ShowWindow( ctypes.windll.kernel32.GetConsoleWindow(), 0) sio = socketio.Client() if not self.config.get('bot_id'): raise Exception('You need to log in first!') @sio.on('connect', namespace='/bot') def connect(): logging.info('Connected') # After connecting, send authentication message sio.emit('auth', { 'bot_id': self.config['bot_id'], 'version': __version__ }, namespace='/bot') @sio.on('run', namespace='/bot') def run(data): logging.info('Running script') logging.info(str(data)) job_id = data['schedule']['job']['id'] # Save backup of the script fn = str(job_id) + '.py' path = os.path.join(os.path.expanduser('~'), fn) with open(path, 'w', newline='') as f: f.write(data['schedule']['script']['code']) cmd = sys.executable + ' -u -m automagica -f ' + path p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.notification('Script {} (job #{}) started.'.format( data['schedule']['script']['name'], data['schedule']['job']['id'])) @sio.on('kill', namespace='/bot') def kill(job): if job == job_id: p.kill() logging.info('Stopping job') # Read STDOUT for line in iter(p.stdout.readline, b''): if line: output = { 'output': line.decode('utf-8'), 'job_id': job_id, 'bot_id': self.config['bot_id'] } sio.emit('output', output, namespace='/bot') # Read STDERR for line in iter(p.stderr.readline, b''): if line: error = { 'error': line.decode('utf-8'), 'job_id': job_id, 'bot_id': self.config['bot_id'] } sio.emit('error', error, namespace='/bot') # Wait for process to finish p.wait() # Retrieve status code code = p.poll() result = { 'job_id': job_id, 'bot_id': self.config['bot_id'], } if code == 0: # Success result['type'] = 'success' else: # Failure result['type'] = 'failure' logging.info('Finished script!') self.notification('Script {} (job #{}) finished.'.format( data['schedule']['script']['name'], data['schedule']['job']['id'])) sio.emit('finish', result, namespace='/bot') @sio.on('disconnect', namespace='/bot') def disconnect(): logging.info('Disconnected') @sio.on('authed', namespace='/bot') def authed(data): logging.info('Authenticated to Automagica as {}'.format( data['bot']['name'])) self.notification('Connected as {} to Automagica!'.format( data['bot']['name'])) @sio.on('error', namespace='/bot') def error(data): logging.info(data.get('error')) try: from tkinter import messagebox messagebox.showwarning('Error', data.get('error')) if data.get('url'): import webbrowser webbrowser.open(data['url']) except: logging.error(data.get('error')) while True: try: sio.connect(self.url) sio.wait() except: logging.info( 'Could not connect to Automagica, retrying in 5 seconds.') sleep(5)
def __init__(self): self.sio = socketio.Client() self.sio = self.__event_wrapper(self.sio)
def listen_on_status_messages(self, alerter_msg_callback=None, dispatcher_msg_callback=None, expiry_msg_callback=None, ingest_msg_callback=None, service_msg_callback=None, service_timing_msg_callback=None, timeout=None): """\ Listen to the various status messages you would find on the UI dashboard. Required (one of): alerter_msg_callback : Callback function when an alerter message is received dispatcher_msg_callback : Callback function when a dispatcher message is received expiry_msg_callback : Callback function when an expiry message is received ingest_msg_callback : Callback function when an ingest message is received service_msg_callback : Callback function when a service message is received service_timing_msg_callback : Callback function when a service timming message is received This function wait indefinitely and calls the appropriate callback for each messages returned """ if dispatcher_msg_callback is None and ingest_msg_callback is None and service_msg_callback is None and \ alerter_msg_callback is None and expiry_msg_callback is None and service_timing_msg_callback is None: raise ClientError( "At least one of the callbacks needs to be defined...", 400) self._sio = socketio.Client(ssl_verify=False) self._stop_on_warning.set_sio(self._sio) if alerter_msg_callback: self._sio.on("AlerterHeartbeat", alerter_msg_callback, namespace='/status') if dispatcher_msg_callback: self._sio.on("DispatcherHeartbeat", dispatcher_msg_callback, namespace='/status') if expiry_msg_callback: self._sio.on("ExpiryHeartbeat", expiry_msg_callback, namespace='/status') if ingest_msg_callback: self._sio.on("IngestHeartbeat", ingest_msg_callback, namespace='/status') if service_msg_callback: self._sio.on("ServiceHeartbeat", service_msg_callback, namespace='/status') if service_timing_msg_callback: self._sio.on("ServiceTimingHeartbeat", service_timing_msg_callback, namespace='/status') self._sio.connect(self._server, namespaces=['/status'], headers=deepcopy(self._header)) self._sio.emit('monitor', { "status": "start", "client": "assemblyline_client" }, namespace='/status') if timeout is None: self._sio.wait() else: self._sio.sleep(timeout) self._sio.disconnect()
'name': USER_NAME }, SECRET, algorithm='HS256') access_token = jwt.encode({ 'id': USER_ID, 'name': USER_NAME }, SECRET, algorithm='HS256') access_token_url_string = "{}".format(access_token.decode('utf-8')) logging.getLogger('socketIO-client').setLevel(logging.DEBUG) logging.basicConfig() sio = socketio.Client(logger=True) @sio.event def message(data): print('I received a message!') @sio.on('connect') def connect_message(): print("connect") @sio.on('startup') def open_startup(data): print("startup=", data)
import socketio, threading, os global conn conn = socketio.Client() class Socket(): @staticmethod @conn.event def connect(): print('Connected!') conn.emit( 'join', { 'nickname': os.environ['redebunda-anticheat-nickname'], 'codigo': os.environ['redebunda-anticheat-codigo'] }) os.environ['redebunda-anticheat-bundaId'] = conn.get_sid() def disconnect(self): conn.disconnect() print('Disconnected!') def connectSocket(self): conn.connect('http://127.0.0.1:5000')
def main(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) logging.info("log_streamer started") # Connect to SocketIO server as client sio = socketio.Client() logging.getLogger("engineio").setLevel(logging.ERROR) sio.connect("http://localhost", namespaces=["/pty"]) @sio.on("connect", namespace="/pty") def on_connect(): logging.info("SocketIO connection established on namespace /pty") @sio.on("pty-log-manager-receiver", namespace="/pty") def process_log_manager(data): with lock: logging.info("EVENT on pty-log-manager-receiver: %s" % data) if data["action"] == "fetch-logs": logging.info("SocketIO action fetch-logs session_uuid %s" % data["session_uuid"]) log_file = LogFile( data["session_uuid"], data["pipeline_uuid"], data["project_uuid"], data["project_path"], data["step_uuid"], ) if "pipeline_run_uuid" in data: log_file.pipeline_run_uuid = data["pipeline_run_uuid"] log_file.experiment_uuid = data["experiment_uuid"] if data["session_uuid"] not in log_file_store: if create_file_handle(log_file): log_file_store[data["session_uuid"]] = log_file logging.info( "Added session_uuid (%s). Sessions active: %d" % (data["session_uuid"], len(log_file_store))) else: logging.error("Adding session_uuid (%s) failed." % data["session_uuid"]) else: logging.warn( "Tried to add %s to log_file_store but it already exists." % data["session_uuid"]) elif data["action"] == "stop-logs": session_uuid = data["session_uuid"] if session_uuid in log_file_store.keys(): clear_log_file(session_uuid) logging.info( "Removed session_uuid (%s). Sessions active: %d" % (session_uuid, len(log_file_store))) else: logging.error( "Tried removing session_uuid (%s) which is not in log_file_store." % session_uuid) elif data["action"] == "heartbeat": session_uuid = data["session_uuid"] if session_uuid in log_file_store.keys(): logging.info("Received heartbeat for session %s" % session_uuid) log_file_store[session_uuid].last_heartbeat = datetime.now( ) else: logging.error( "Received heartbeat for log_file with session_uuid %s that isn't registered." % session_uuid) # Initialize file reader loop file_reader_loop(sio)
import socketio host = 'raasta.herokuapp.com' port = 80 # host = '0.0.0.0' # port = 5000 sio_client = socketio.Client(reconnection=True) sio_client.connect("http://" + str(host) + ":" + str(port), namespaces = ['/']) @sio_client.event def transit_data(data): print(data) @sio_client.event def connect(): print("connected to server")
import socketio from game_functions import * from board import humanBoard tournament_data = { 'user_name': 'carlos_chew', 'tournament_id': 12 } server_address = 'http://*****:*****@socket.on('connect') def connection_event(): data = tournament_data if('user_name' in data.keys() and 'tournament_id' in data.keys()): data.update({'user_role':'player'}) print(f'Iniciando sesion: {data}') socket.emit('signin', data) @socket.on('ok_signin') def signin_event(): print(f'Sesion iniciada') @socket.on('ready') def move_event(data): print(f'Nuevo tablero recibido: {data}') data.update({ 'movement': get_new_move(),
import socketio import time import Adafruit_DHT DHT_SENSOR = Adafruit_DHT.DHT11 DHT_PIN = 4 # humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN) sio = socketio.Client() # client açma işlemi connected = False time.sleep(5) while not connected: try: sio.connect("http://10.11.22.179:5000") #socketio ya bağlanılması connected = True except: print("baglaniliyor") time.sleep(0.3) sayac = 0 succes = False while True: humidity, temperature = Adafruit_DHT.read( DHT_SENSOR, DHT_PIN) # sensör değerinin alınması msg = "sayac = {0} nem = {1} , sicaklik = {2}".format( sayac, humidity, temperature) sio.emit( "message", msg ) #emit send gibi bir komut ve emit sayesinde istenilen event'e veri gönderebiliyoruz #msg nin olduğu yere callback fonsiyonu da gelebilir aslında biz sadece değişken değil fonksiyon da gönderebiliyoruz sayac = sayac + 1 time.sleep(1)
import socketio # standard Python sio = socketio.Client() def setup(): sio.connect('http://raspberrypi:5000') def send_action(action, value): sio.emit('action', {'direction': action, 'value': value}) def disconnect(): sio.disconnect()
class check_socketio: """ check_socketio: Check socketio connection without authentification. Possible found message, logs or other traces """ sio = socketio.Client(reconnection=False) dynamic_function_number = 0 def connect(self, url, path): try: #print(url+path) #DEBUG self.sio.connect(url, socketio_path=path) return True except Exception as e: #print(e) #DEBUG if "www." in url: urli = url.replace("www.","") self.connect(urli, path) return e return False def disconnect(self): try: self.sio.disconnect() except: pass def run_socketio(self, url, poutput): """ run_socketio: Try socketio connection """ found_socket = False for path in socketio_paths: connect = self.connect(url, path) if type(connect) == bool and connect: print(" {} {}{} found !".format(PLUS, url, path)) domain = url.split("/")[2] if not "www" in url else ".".join(url.split("/")[2].split(".")[1:]) print(" {} Try this \"\033[36msudo apt install npm -y && npx wscat -c ws://{}/socket.io/?transport=websocket\033[0m\" \n If you have a 30X redirection you can try with 'wss://'".format(INFO, domain)) self.disconnect() found_socket = True elif not found_socket and poutput: print(" \033[33m\u251c \033[0m {}{}: {}".format(url, path, connect)) if not found_socket: print(" \033[33m{}\033[0m Nothing Socketio found".format(LESS)) def main_socketio(self, url): print("\033[36m Websockets \033[0m") print(LINE) if "www." in url: urls = [] urls.append(url) urls.append(url.replace("www.", "")) for u in urls: print(" \033[34m\u251c\033[0m {}".format(u)) self.run_socketio(u, poutput=False) else: self.run_socketio(url, poutput=True)
import time import requests import json import base64 import hmac import hashlib import socketio socket_IO = socketio.Client() class bitbnsApi(): apiKeys = dict() baseUrl = 'https://api.bitbns.com/api/trade/v1' baseUrl2 = 'https://api.bitbns.com/api/trade/v2' def __init__(self, apiKey, apiSecretKey): self.apiKeys['apiKey'] = apiKey self.apiKeys['apiSecretKey'] = apiSecretKey headers = { 'X-BITBNS-APIKEY': apiKey, } response = requests.get( 'https://api.bitbns.com/api/trade/v1/getServerTime', headers=headers) response = response.json() serverTime = int(response['serverTime']) localTime = int(time.time() * 1000.0) self.timeOffset = localTime - serverTime
class DoorStatus: # A socket.io client is created sio = socketio.Client() # data variable is defined in the class level. data = None # json_file_path = None def __init__(self, in_json_file_path): global json_file_path, driver json_file_path = in_json_file_path self.json_file_path = in_json_file_path print("door_status.py -> __init__() -> self.json_file_path = ", self.json_file_path) @staticmethod def door_status_handler(data=None): print("data is received: ", data) with open(json_file_path, 'r+') as data_file: data_file.truncate(0) json.dump(data, data_file) if data['status'] in [0,1,2]: DoorStatus.sio.disconnect() # write data in a json file # @classmethod # def door_status_handler(cls,data=None): # print() # print("data is received: ", data) # print("json_file_path = ", cls.json_file_path) # #print("type(self)",end="") # #print(type(self)) # #print("self", self) # print() # with open(cls.json_file_path, 'w') as data_file: # json.dump(data, data_file) # # json.dump(data,self) # #data = self.copy() # if data['status'] == 1: # DoorStatus.sio.disconnect() # def door_status_handler(self,data=None): # print() # print("data is received: ", data) # print("json_file_path = ", DoorStatus.json_file_path) # #print("type(self)",end="") # #print(type(self)) # print("self", self) # print() # # with open(json_file_path, 'w') as data_file: # # json.dump(data, data_file) # # json.dump(data,self) # data = self.copy() # # if data['status'] == 0: # DoorStatus.sio.disconnect() # Receive data @staticmethod def door_connection_handler(data=None): # print() # print("door_status.py -> door_connection_handler() -> data = ", data) # print() return data @sio.event def connect(self=None): # print() # print("door_status.py -> connect() -> self = ", self) # print() DoorStatus.sio.on("connection", DoorStatus.door_connection_handler) DoorStatus.sio.emit("subscribe", {"office_id": 1}) DoorStatus.sio.on("door_status_notify", DoorStatus.door_status_handler) DoorStatus.sio.emit("get_door_status", {"door_id": 234523, "office_id": 1}) # Disconnect from the server @sio.event() def disconnect(): DoorStatus.sio.disconnect() DoorStatus.sio.eio.disconnect(True) # Connect to the server @staticmethod def connect_socketio(): url = base_config.Configuration.get_base_url() # print() # print("door_status.py -> connect_socketio() -> url = " + url) # print() password = base_config.Configuration.get_mobile_device_password() # print() # print("door_status.py -> connect_socketio() -> password = "******"door_status.py -> connect_socketio() -> path = " + path) # print() DoorStatus.sio.connect(url + password, socketio_path=path) DoorStatus.sio.wait() # print() # print("door_status.py -> connect_socketio() -> HERE1") # print() # Disconnect from the socket.io @staticmethod def disconnect_socketio(): DoorStatus.sio.disconnect() DoorStatus.sio.eio.disconnect(True)