def __init__(self, app, skip=None): try: Bdb.__init__(self, skip=skip) except TypeError: Bdb.__init__(self) self.begun = False self.app = app self.ws = WebSocket('0.0.0.0', randint(10000, 60000)) self.connected = False tries = 1 while self.ws == 'FAIL' and tries < 10: tries += 1 self.ws = WebSocket('0.0.0.0', randint(10000, 60000))
def __init__(self, url, on_open=None, on_message=None, on_error=None, on_close=None, symbol='btc_cny'): """ url: websocket url. on_open: callable object which is called at opening websocket. this function has one argument. The arugment is this class object. on_message: callbale object which is called when recieved data. on_message has 2 arguments. The 1st arugment is this class object. The passing 2nd arugment is utf-8 string which we get from the server. on_error: callable object which is called when we get error. on_error has 2 arguments. The 1st arugment is this class object. The passing 2nd arugment is exception object. on_close: callable object which is called when closed the connection. this function has one argument. The arugment is this class object. """ self.url = url self.sock = WebSocket() self.sock.connect(self.url) self.symbol = ''.join(symbol.split('_')) self.send("{'event':'addChannel','channel':'ok_%s_depth'}" % self.symbol)
def run_application(self): path = self.environ.get('PATH_INFO') content_type = self.server.data_handlers.get(path) if content_type is not None: self.serve_file(basename(path), content_type) return websocket_mode = False if WebSocket.is_socket(self.environ): self.status = 'websocket' self.log_request() self.environ['websocket'] = WebSocket(self.environ, self.socket, self.rfile) websocket_mode = True try: self.result = self.application(self.environ, self.start_response) if self.result is not None: self.process_result() except: websocket = self.environ.get('websocket') if websocket is not None: websocket.close() raise finally: if websocket_mode: # we own the socket now, make sure pywsgi does not try to read from it: self.socket = None
def _connect(self, auth): self.ws = WebSocket(sslopt={'check_hostname': False}) self.ws.connect(url=self.connection.ws_url) debug('Connected to Showdown socket') msg = '' while not msg.startswith('|challstr|'): msg = self.ws.recv() challstr = msg[msg.find('|challstr|') + len('|challstr|'):] if auth == 'register': self.username = generate_username() self.password = generate_token(16) assertion = register(challstr=challstr, username=self.username, password=self.password) elif isfile(auth): with open(auth, 'r') as file: self.username, password = file.read().splitlines() self.password = None assertion = login(challstr=challstr, username=self.username, password=password) else: self.username = generate_username() self.password = None assertion = auth_temp_user(challstr=challstr, username=self.username) login_cmd = f'|/trn {self.username},0,{assertion}' self.ws.send(login_cmd) msg = '' while not msg.startswith('|updateuser|') and self.username not in msg: msg = self.ws.recv() debug(msg)
def __init__(self, configuration, url, headers): """A websocket client with support for channels. Exec command uses different channels for different streams. for example, 0 is stdin, 1 is stdout and 2 is stderr. Some other API calls like port forwarding can forward different pods' streams to different channels. """ enableTrace(False) header = [] self._connected = False self._channels = {} self._all = "" # We just need to pass the Authorization, ignore all the other # http headers we get from the generated code if headers and 'authorization' in headers: header.append("authorization: %s" % headers['authorization']) if url.startswith('wss://') and configuration.verify_ssl: ssl_opts = { 'cert_reqs': ssl.CERT_REQUIRED, 'keyfile': configuration.key_file, 'certfile': configuration.cert_file, 'ca_certs': configuration.ssl_ca_cert or certifi.where(), } if configuration.assert_hostname is not None: ssl_opts['check_hostname'] = configuration.assert_hostname else: ssl_opts = {'cert_reqs': ssl.CERT_NONE} self.sock = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False) self.sock.connect(url, header=header) self._connected = True
def __init__(self, *args, **kwargs): super(Websocket, self).__init__(*args, **kwargs) self.scheme = 'ws' self.connection = WebSocket() self.reading = False self.writing = False self.read_loop = None
def proxy_socket(ws, path): # create connection to the remote: keep_headers = ['cookie'] request_headers = { name: value for (name, value) in request.headers.items() if name.lower() in keep_headers } pws = WebSocket(enable_multithread=True) pws.connect(f"ws://{SITE_NAME}flexx/ws/{path}", header=request_headers) # start remote handler: remote_handler_thread = threading.Thread(target=remote_handler, args=(ws, pws)) remote_handler_thread.start() # pws = create_connection(f"ws://{SITE_NAME}flexx/{request.full_path}", header=request_headers, class_=MyWebSocket) while not ws.closed: message = ws.receive() if isinstance(message, (bytearray, bytes)): opcode = ABNF.OPCODE_BINARY elif isinstance(message, str): opcode = ABNF.OPCODE_TEXT elif message is None: assert ws.closed break else: raise ValueError('Unknown message type') pws.send(message, opcode=opcode) pws.close() return
def create(cls, server=None): # type: (Optional[server.SDKServer]) -> USDKConnection server = server or get_instance() websocket = WebSocket() websocket.connect("ws://localhost:{}/eyes".format(server.port)) websocket.settimeout(20 * 60) return cls(websocket, server.log_file_name)
def __init__( self, address: str, port: int, subscription_type: Optional[str] = None, filters: Optional[Dict[str, Any]] = None ): """Subscriber constructor. Parameters ---------- address: str IP address of the Exonum node. port: int Port of the exonum node. subscription_type: Optional[str] Type of subscription: "blocks" or "transactions". If not given, it is assumed that subscriber is used to send transactions. filters: Optional[Dict[str, Any]] Dictionary of filters, such as 'service_id' and 'tx_id' for transactions. """ if not subscription_type: self._address = self.SENDING_WEBSOCKET_URI.format(address, port) else: if subscription_type not in Subscriber.SUBSCRIPTION_TYPES: err = ValueError( f"Subscription type must be one of these: {self.SUBSCRIPTION_TYPES}, " f"while {subscription_type} is given." ) logger.error("Error occurred during subscriber initialization: %s", err) raise err parameters = "?" + urlencode(filters) if filters else "" self._address = self.SUBSCRIPTION_WEBSOCKET_URI.format(address, port, subscription_type) + parameters self._is_running = False self._connected = False self._ws_client = WebSocket() self._thread = Thread(target=self._event_processing) self._handler: Optional[Subscriber.CallbackType] = None
def obs_ws_connect(buffer_queue, host, port, password): ws = WebSocket() try: ws.connect(f'ws://{host}:{port}') ws.send(json.dumps({ "request-type": "GetAuthRequired", "message-id": "1" })) res = json.loads(ws.recv()) if res['status'] != 'ok': buffer_queue.put(('ERR', res['error'])) return None if res.get('authRequired'): sec = base64.b64encode(hashlib.sha256((password + res['salt']).encode('utf-8')).digest()) auth = base64.b64encode(hashlib.sha256(sec + res['challenge'].encode('utf-8')).digest()).decode('utf-8') ws.send(json.dumps({"request-type": "Authenticate", "message-id": '2', "auth": auth})) res = json.loads(ws.recv()) if res['status'] != 'ok': self.buffer_queue.put(('ERR', res['error'])) return None return ws except socket.error as error: buffer_queue.put(('ERR', error)) return None
def send_transaction(self, message: ExonumMessage) -> str: """ Sends a transaction into an Exonum node via WebSocket. Example: >>> response = client.send_websocket_transaction(message) >>> print(response) {"result":"success","response":{"tx_hash":"48b7d71d388f3c2dfa665bcf837e1fa0417ca559fb0163533ea72de6319e61ca"}} Parameters ---------- message: ExonumMessage Prepared and signed an Exonum message. Returns ------- result: str Result of the WebSocket request. If a transaction is correct and it is accepted, it will contain a JSON with a hash of the transaction. """ body_raw = message.signed_raw() if body_raw is None: logger.critical("Attempt to send an unsigned message through websocket.") raise RuntimeError("Attempt to send an unsigned message.") data = json.dumps({"type": "transaction", "payload": {"tx_body": body_raw.hex()}}) ws_client = WebSocket() ws_client.connect(self._address) ws_client.send(data) response = ws_client.recv() ws_client.close() return response
def get_gluware_version(addr): message = None ssl_cert_off = {"cert_reqs": CERT_NONE} # Turn off SSL certificate checking ws = WebSocket(sslopt=ssl_cert_off) try: ws.connect( 'wss://{address}/ControlApi/socket.io/?EIO=3&transport=websocket'. format(address=addr)) except ws_exception.WebSocketBadStatusException as con_error: print('Connection error: {info}'.format(info=con_error)) return ws.send( '421["request",{"service":"DocsService","method":"getVersion","payload":{}}]' ) while True: message = ws.recv() #print(message) if not message: print('Empty message') return if 'gluware_version' in message: break json_string = message[4:-1] json_payload = loads(json_string)['payload'] payload = loads(json_payload) return payload['gluware_version']['semver']
def test(self, port=None, prefix="", scheme="http"): """ kosmos `j.tools.packages.webinterface.test()' :return: """ base_url = "0.0.0.0" if port: base_url = base_url + f":{port}" if prefix: base_url = base_url + f"/{prefix}" url = f"{scheme}://{base_url}" j.servers.threebot.start(background=True) gedis_client = j.clients.gedis.get( name="default", host="127.0.0.1", port=8901, package_name="zerobot.packagemanager" ) gedis_client.actors.package_manager.package_add( j.core.tools.text_replace( "{DIR_BASE}/code/github/threefoldtech/jumpscaleX_core/JumpscaleCore/servers/gedis/pytests/test_package" ) ) gedis_client.reload() print("testing gedis http") assert ( j.clients.http.post( f"{url}/zerobot/test_package/actors/actor/echo", data=b'{"args":{"_input":"hello world"}}', headers={"Content-Type": "application/json"}, ) .read() .decode() == "hello world" ) print("gedis http OK") print("testing gedis websocker") from websocket import WebSocket import ssl ws = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) ws.connect(f"wss://{base_url}/gedis/websocket") assert ws.connected payload = """{ "namespace": "default", "actor": "echo", "command": "actor.echo", "args": {"_input": "hello world"}, "headers": {"response_type":"json"} }""" ws.send(payload) assert ws.recv() == "hello world" print("gedis websocket OK") print("tearDown") gedis_client.actors.package_manager.package_delete("zerobot.test_package") j.servers.threebot.default.stop()
def __init__(self, controlSock, clientAddr, ifPrimitive, root, ip_management): super(Server, self).__init__() self.daemon = True self.bufSize = 2000000000 self.ifPrimitive = ifPrimitive if ifPrimitive: self.controlSock = controlSock else: self.controlSock = WebSocket(controlSock, self.bufSize) self.clientAddr = clientAddr self.dataListenSock = None self.dataAddr = '127.0.0.1' self.dataPort = None self.username = '' self.authenticated = False self.if_administrator = False self.cwd = root self.root_wd = root self.typeMode = 'Binary' self.dataMode = 'PORT' self.nlst_data_socket = None self.retr_data_socket = None self.stor_data_socket = None self.ip_data_socket = None self.data_socket_for = 'NLST' self.ip_management = ip_management
def connect_slack_websocket(self, ws_url): """Uses http proxy if available""" if self.proxies and 'http' in self.proxies: parts = parse_url(self.proxies['http']) proxy_host, proxy_port = parts.host, parts.port auth = parts.auth proxy_auth = auth and auth.split(':') else: proxy_auth, proxy_port, proxy_host = None, None, None try: #self.websocket = create_connection(ws_url, # http_proxy_host=proxy_host, # http_proxy_port=proxy_port, # http_proxy_auth=proxy_auth) self.websocket = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.websocket.connect(ws_url, http_proxy_host=proxy_host, http_proxy_port=proxy_port, http_proxy_auth=proxy_auth) self.connected = True self.last_connected_at = time.time() logging.debug("RTM connected") self.websocket.sock.setblocking(0) except Exception as e: self.connected = False raise SlackConnectionError(message=str(e))
def send_message(msg_type, data): panel_config = load_config() ws = WebSocket() ws.connect("ws://" + panel_config['uri'][0] + "/core") message = '{"type": "' + msg_type + '", "data":' + data + '}' ws.send(message) ws.recv() ws.close()
def setUp(self): self.ws = WebSocket(sslopt={'check_hostname': False}) self.ws.connect(url='wss://sim.smogon.com/showdown/websocket') msg = '' while not msg.startswith('|challstr|'): msg = self.ws.recv() self.challstr = msg[msg.find('|challstr|') + len('|challstr|'):] self.ws.settimeout(.5)
def test_echo(server): ws = WebSocket() ws.connect(f'ws://127.0.0.1:{server}') ws.send('Hello World!') data = json.loads(ws.recv()) assert {'msg': 'Hello World!', 'id': 1} == data data = json.loads(ws.recv()) assert {'msg': 'Hello World!', 'id': 1} == data
def test_socket(self): mock_socket = MockSocket() c = WebSocket('ws://localhost:1234/', MockSocketFactory(mock_socket)) c.connect() c.send("Rock it with HTML5 WebSocket") msg = c.receive() c.close() print(msg)
def pi_boot_fn(): def my_msg_handler(msg): print 'Got "%s"!' % msg socket = WebSocket('ws://localhost:8888/enginebus/were', onmessage=my_msg_handler) socket.onopen = lambda: socket.send('Hello world!') try: asyncore.loop() except KeyboardInterrupt: socket.close()
def TESTSocketandRequest(token): ws_url = "ws://{}:{}/connectToServer".format(base_url, port) ws = WebSocket() print('*Connecting Socket*') ws.connect(ws_url) print('*Sending Login Token To Authenticate Socket Gateway*') ws.send(dumps({"tok": token})) print('*Socket Connection Status*', ws.recv()) print('Simulating A Demo Requests') TESTRequest() print('Request Submitted') return loads(ws.recv())
def follow(filename): url = 'ws://localhost:9292/follow/{}'.format(filename) ws = WebSocket() try: ws.connect(url) while True: msg = ws.recv() print('{} :: {}'.format(filename, msg), end='') finally: # ws.close() takes forever ws.shutdown()
def __init__(self, configuration, url, headers, capture_all): """A websocket client with support for channels. Exec command uses different channels for different streams. for example, 0 is stdin, 1 is stdout and 2 is stderr. Some other API calls like port forwarding can forward different pods' streams to different channels. """ enableTrace(False) header = [] self._connected = False self._channels = {} self._ordered_all = [] if capture_all: self._all = StringIO() else: self._all = _IgnoredIO() # We just need to pass the Authorization, ignore all the other # http headers we get from the generated code if headers and 'authorization' in headers: header.append("authorization: %s" % headers['authorization']) if headers and 'sec-websocket-protocol' in headers: header.append("sec-websocket-protocol: %s" % headers['sec-websocket-protocol']) else: header.append("sec-websocket-protocol: v4.channel.k8s.io") if url.startswith('wss://') and configuration.verify_ssl: ssl_opts = { 'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': configuration.ssl_ca_cert or certifi.where(), } if configuration.assert_hostname is not None: ssl_opts['check_hostname'] = configuration.assert_hostname else: ssl_opts = {'cert_reqs': ssl.CERT_NONE} if configuration.cert_file: ssl_opts['certfile'] = configuration.cert_file if configuration.key_file: ssl_opts['keyfile'] = configuration.key_file self.sock = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False) if configuration.proxy: proxy_url = urlparse(configuration.proxy) self.sock.connect(url, header=header, http_proxy_host=proxy_url.hostname, http_proxy_port=proxy_url.port) else: self.sock.connect(url, header=header) self._connected = True
def connect(self): """Connect to the endpoint and return the opened websocket""" log.debug("Connecting to {ws_endpoint} ...".format(ws_endpoint=self.ws_endpoint)) ws = self.ws = WebSocket() ws.connect(self.ws_endpoint) # Alias websocket-client's recv command to receieve so that # it's compatible with gevent-websocket: ws.receive = ws.recv # Authenticate: cmd = receive_data(ws) self.__authenticate(cmd) self.__server_synced = True return ws
def __init__(self, parent, logger, callBack): super(NetworkingThread, self).__init__() self.room = parent.room self.parent = parent self.logger = logger self.cb = callBack self.daemon = True self.name = "{}-NetworkingThread".format(self.room.roomId) self.connection = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.callBackThread = CallBackThread(self.room, self.logger) self.heartBeatThread = Thread(target=self.heartBeat, daemon=True, name=f"{self.room.roomId}-HeartBeat") self.binaryDataQueue = Queue(100) self.dataQueue = Queue(100) self.run_flag = True
def connect(self, just_check=False): if just_check: if not self.connection.connected: self.logger.info("ws掉线, 正在重连") self.connection = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self.connection.connect(self.room.roomWsUrl) if self.connection.connected: self.logger.info("ws连接创建, 已连接") elif not self.connection.connected: self.connection.connect(self.room.roomWsUrl) if self.connection.connected: self.logger.info("ws连接创建, 已连接") self.run_flag = True self.start()
def test_websocket_connection(): ws_user = WebSocket() ws_agent = WebSocket() sender_id = str(np.random.randint(1234562523))+"_"+"john123" ws_user.connect(env_config['RASA_URL']) ws_agent.connect(env_config['RASA_URL']) ws_user.send(login(sender_id)) received_data=ws_user.recv() ws_user.send(send_msg(sender_id,'Hi')) received_data=ws_user.recv() ws_user.send(send_msg(sender_id,'Yes')) received_data=ws_user.recv() ws_agent.send(login('HA_agent5+'+sender_id)) received_data=ws_agent.recv() ws_user.send(send_msg(sender_id,'Yes')) received_data=ws_user.recv() ws_user.send(send_msg(sender_id,'ok')) received_data = requests.get(env_config['conv_listen_address'] + "?sender_id=" + sender_id) ws_agent.send(send_msg('HA_agent5+'+sender_id, "Hi john, Your payoff amount is $1461")) received_data=ws_user.recv() ws_user.send(send_msg(sender_id,"ok")) return 'success'
def test_websocket_proxy(): """ kosmos -p 'j.servers.openresty.test(name="websocket_proxy")' kosmos 'j.servers.openresty.test(name="websocket_proxy")' :return: """ # start echo websocket proxy server cmd = """ from Jumpscale import j rack = j.servers.rack.get() rack.websocket_server_add("test", port=4444) rack.start() """ s = j.servers.startupcmd.get(name="websocket_test_server", cmd_start=cmd, interpreter="python", executor="tmux", ports=[4444]) s.start() server = j.servers.openresty.get("test") server.stop() server.install(reset=True) server.configure() website = server.websites.get("test3") website.ssl = False locations = website.locations.get("websocket_proxied") proxy_location = locations.locations_proxy.new() proxy_location.name = "proxy2" proxy_location.path_url = "/" proxy_location.ipaddr_dest = "0.0.0.0" proxy_location.port_dest = "4444" proxy_location.type = "websocket" proxy_location.scheme = "http" locations.configure() website.configure() server.start() from websocket import WebSocket ws = WebSocket() ws.connect("ws://0.0.0.0/") assert ws.connected website.delete() server.cleanup() server.stop()
def __init__(self, address: str, port: int): """Subscriber constructor. Parameters ---------- address: str IP address of the Exonum node. post: int Port of the exonum node. """ self._address = _WEBSOCKET_URI.format(address, port) self._is_running = False self._connected = False self._ws_client = WebSocket() self._thread = Thread(target=self._event_processing) self._handler: Optional[Subscriber.CallbackType] = None
def __init__(self): CarlaHostQtNull.__init__(self) self.host = "localhost" self.port = 2228 self.baseurl = "http://{}:{}".format(self.host, self.port) self.socket = WebSocket() self.socket.connect("ws://{}:{}/ws".format(self.host, self.port), timeout=1) self.isRemote = True self.isRunning = True self.peaks = [] for i in range(99): self.peaks.append((0.0, 0.0, 0.0, 0.0))