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)
class Slack(object): """Simple class which just allows sending of messages via Slack""" base_url = "https://slack.com/api/" def __init__(self, token=irakli_is_bad): self.token = token response = requests.get(Slack.base_url + 'rtm.start', params={"token": token}) body = response.json() self.channels = {c["name"]: c for c in chain(body["channels"], body["groups"])} url = body["url"] self.socket = WebSocket() self.socket.connect(url) self.socket.settimeout(5) self.message_id = 0 def send_message(self, channel_name, text): """Send a message TODO:? Verify success """ message = json.dumps({"id": self.message_id, "type": "message", "channel": self.channels[channel_name]["id"], "text": text}) self.message_id += 1 self.socket.send(message) def close(self): self.socket.close()
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()
class _App(WebSocketApp): def __init__(self, *args, **kwargs): super(_App, self).__init__(*args, **kwargs) self.keep_running = True def run_forever(self): """ run event loop for WebSocket framework. This loop is infinite loop and is alive during websocket is available. """ if self.sock: raise WebSocketException('Socket already exists') try: self.sock = WebSocket() self.sock.connect(self.url) sleep(2) self._run_with_no_err(self.on_open) while self.keep_running: data = self.sock.recv() if data is None: break self._run_with_no_err(self.on_message, data) except Exception, e: self._run_with_no_err(self.on_error, e) finally:
class RPANChat: def __init__(self, user_agent: str): self._header = {'User-Agent': user_agent} self._websocket = WebSocket() def __iter__(self): while True: try: comment_data = self._websocket.recv() except WebSocketConnectionClosedException: return comment_json = json.loads(comment_data) if comment_json['type'] != 'new_comment': continue payload = comment_json['payload'] author = payload['author'] body = payload['body'] created_utc = payload['created_utc'] id = payload['_id36'] yield RPANComment(author, body, created_utc, id) def connect(self, stream_id: str) -> None: strapi_request = requests.get( f'https://strapi.reddit.com/videos/t3_{stream_id}', headers=self._header) if strapi_request.status_code != 200: raise ConnectionError stream_json = strapi_request.json() live_comments_websocket = stream_json['data']['post'][ 'liveCommentsWebsocket'] self._websocket.connect(live_comments_websocket, header=self._header) def disconnect(self) -> None: self._websocket.close()
class TestAuthentication(TestCase): 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_auth_temp_user(self): username = generate_username() assertion = auth_temp_user(self.challstr, username) login_cmd = f'|/trn {username},0,{assertion}' self.ws.send(login_cmd) self._username_in_msg(username) def test_login(self): with open('ts_auth.txt', 'r') as file: username, password = file.read().splitlines() assertion = login(self.challstr, username, password) login_cmd = f'|/trn {username},0,{assertion}' self.ws.send(login_cmd) self._username_in_msg(username) def _username_in_msg(self, username): msg = '' while not msg.startswith('|updateuser|'): msg = self.ws.recv() self.assertIn(username, msg) def tearDown(self): self.ws.close()
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
class WSS: url: str = settings.WEB_SOCKET_SERVER wss: WebSocket = field(init=False) def __post_init__(self): self.wss = WebSocket() def connect(self): self.wss.connect(self.url) message = "Открываем соединение с Web Socket Server" logger.debug(message) self.wss.send(message) def publish(self, message: str, is_mute=False) -> None: is_test = settings.TEST is False is_debug = settings.DEBUG is False is_wss_mute = is_mute is False if is_test and is_debug and is_wss_mute: if self.wss.sock is None: self.connect() self.wss.send(message) def close(self): try: message = "Закрываем соеденение с Web Socket Server" self.wss.send(message) logger.debug(message) self.wss.close() except WebSocketConnectionClosedException: pass
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 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
class client(): def __init__(self): self.ws = WebSocket() def __enter__(self): self.ws.connect(WS_PATH) return self def __exit__(self, *exc): self.ws.close() def send(self, commands): list(map(self.ws.send, commands)) def daylight(self, level): self.send(dimmer(level)) self.send(led(level, 1, 0.75, 0.5)) def house(self, level): self.send(dimmer(level * 0.2)) self.send(led(level * 0.4, 1, 0.25, 0.02)) def flash(self): self.send(dimmer(0)) self.send(led(1, 1, 1, 1)) time.sleep(0.1) self.send(led(0, 0, 0, 0)) def end(self, level): self.send(dimmer(0)) self.send(led(level * .5, 0, 0, 1)) def blackout(self): self.send(dimmer(0)) self.send(led(0, 0, 0, 0))
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 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()
class Websocket(Transport): name = 'websocket' 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 get_uri(self): query = {'EIO': '3', 'transport': self.name} if self.client and self.client.sid: query['sid'] = self.client.sid querystring = urllib.parse.urlencode(query) return '%s://%s:%d%s/?%s' % (self.scheme, self.hostname, self.port, self.path, querystring) def loop_read(self): while self.state in ['opening', 'open']: if self.state == 'opening': self.handle_open() packet = self.read() packet = self.parser.decode_packet(packet) self.handle_packet(packet) def do_open(self): self.connection.connect(self.get_uri()) self.read_loop = self.client.start_loop(self.loop_read) def do_close(self): def close(): self.send([Packet(Packet.CLOSE)]) self.client.stop_loop(self.read_loop) if self.state == 'open': close() else: self.once('open', close) def do_send(self, packets): for packet in packets: enc_packet = self.parser.encode_packet(packet) self.write(enc_packet) def read(self): self.reading = True packet = self.connection.recv() return packet def write(self, packet): self.writing = True logger.debug('Sending payload: %s' % repr(packet)) self.connection.send(packet)
class WebSocketApp(object): """ Higher level of APIs are provided. The interface is like JavaScript WebSocket object. """ 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 send(self, data): """ send message. data must be utf-8 string or unicode. """ self.sock.send(data) def close(self): """ close websocket connection. """ self.sock.close() def depth(self, symbol='btc_cny'): try: data = self.sock.recv() resp = json.loads(data) return resp[0]['data'] except Exception as e: logging.info("except[%s]" % e) def _run_with_no_err(self, callback, *args): if callback: try: callback(self, *args) except Exception as e: if logger.isEnabledFor(logging.DEBUG): logger.error(e)
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 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()
class Client(): _instance = None @staticmethod def Get(): if Client._instance is None: Client._instance = Client() return Client._instance def __init__(self): self.socket = WebSocket() self.userId = random.randint(0, 65536) def Start(self): import configReader serverIp = configReader.ConfigReader.GetVariable('SERVER_IP') serverPort = configReader.ConfigReader.GetVariable('PORT') self.socket.connect('ws://' + serverIp + ':' + serverPort + '/') messageData = {'user_id' : self.userId} message = '[playerJoined, ' + json.dumps(messageData) + ']' self.socket.send(message) engine.Engine.Get().Start() self.Close() def GetMessage(self): messageData = self.socket.recv() return json.loads(messageData) def SendPlayerMovedMessage(self, factor): messageData = {'user_id' : self.userId, 'factor' : factor} message = '[playerMoved, ' + json.dumps(messageData) + ']' self.socket.send(message) def SendPlayerTurnedMessage(self, factor): messageData = {'user_id' : self.userId, 'factor' : factor} message = '[playerTurned, ' + json.dumps(messageData) + ']' self.socket.send(message) def SendPlayerFiredMessage(self): messageData = {'user_id' : self.userId} message = '[playerFired, ' + json.dumps(messageData) + ']' self.socket.send(message) def Close(self): self.socket.close()
class Gateway: def __init__(self, url): self.url = url self.ws = WebSocket() self.close_reason = None self.limiter = GatewayRateLimiter() def __iter__(self): try: self.ws.connect(self.url) except WebSocketError as e: logger.debug("Exception connecting to gateway.", exc_info=True) self.close_reason = CloseReason.exception(e) while self.ws.connected: try: with self.ws.readlock: opcode, data = self.ws.recv_data() except WebSocketError as e: logger.debug("Exception receiving gateway data.", exc_info=True) self.close_reason = CloseReason.exception(e) break if data and opcode == ABNF.OPCODE_CLOSE: self.close_reason = CloseReason.parse(data) break if data and opcode == ABNF.OPCODE_TEXT: decoded_data = data.decode("utf-8") logger.debug("Gateway payload received: %s", decoded_data) yield JsonObject(json.loads(decoded_data)) logger.info("Gateway Closed: %s", self.close_reason) def send(self, data): self.limiter.on_send() payload = json.dumps(data) logger.debug("Gateway payload sent: %s", payload) try: self.ws.send(payload) except WebSocketError: logger.debug("Error sending payload.", exc_info=True) raise NetworkError def close(self, status=1000): # An error is output be websocket-client for non-1000 statuses. # During normal operation we use non-1000 statuses and don't want an error logged. with suppress_logging("websocket"): self.ws.close(status=status)
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()
class client(object): stopping = False greenlets = None def __init__(self, args, url): self.args = args self.tuntap = tuntap.tuntap(args.tuntap) self.ws = WebSocket() self.ws.connect(url) self.greenlets = [ gevent.spawn(self.read_ws), gevent.spawn(self.read_fd) ] def read_fd(self): while not self.stopping: try: msg = os.tp_read(self.tuntap.fd, 1500) if not self.ws.connected: break if not msg: self.stopping = True self.ws.close() break except IOError: break self.ws.send_binary(msg) def read_ws(self): while not self.stopping: try: msg = self.ws.recv() if not msg: break except websocket.WebSocketConnectionClosedException: self.stopping = True self.greenlets[1].kill() break except: continue os.tp_write(self.tuntap.fd, bytes(msg)) def join(self): gevent.joinall(self.greenlets)
def assert_can_connect_websockets(self, ws_uri): try: ws = WebSocket() ws.connect(ws_uri) except WebSocketException: success = False else: success = True finally: self.entry['assertions'].append({ 'name': 'test can connect to websockets', 'success': success, })
class WSTunnel: def __init__(self, *args, **kwargs): self.ws = WebSocket(*args, **kwargs) def send(self, data): return self.ws.send_binary(data) def recv(self): return self.ws.recv() def connect(self, *args, **kwargs): self.ws.connect(*args, **kwargs) def up(self): pass def down(self): self.ws.close()
def callback(self, instance, value): print('O switch', instance, 'is', value) app = App.get_running_app() client = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) try: app.start(1000, 0) client.connect(address.ADDRESS_WEBSOCKET) time.sleep(5) client.send(app.gps_location + "\n" + app.username) except Exception as e: print(e) finally: app.stop() client.close() value = False
class Gateway: def __init__(self, url): self.url = url self.ws = WebSocket() def __iter__(self): self.ws.connect(self.url) for data in self.ws: if data: yield data if not self.ws.connected: break def send(self, data): self.ws.send(data) def close(self): self.ws.close()
def create_websocket(configuration, url, headers=None): enableTrace(False) # We just need to pass the Authorization, ignore all the other # http headers we get from the generated code header = [] 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 websocket = WebSocket(sslopt=ssl_opts, skip_utf8_validation=False) connect_opt = { 'header': header } if configuration.proxy or configuration.proxy_headers: connect_opt = websocket_proxycare(connect_opt, configuration, url, headers) websocket.connect(url, **connect_opt) return websocket
def update(): db = MongoClient('213.183.48.116').golos ws = WebSocket() ws.connect('wss://api.golos.cf') print('Starting update') for post in db.posts.find(): ws.send( dumps({ "id": 1, "method": "get_content", "params": [post['author'], post['permlink']] })) ids = post['id'] response = eval(ws.recv())['result'] db.posts.update({'id': ids}, { '$set': { 'reward': response['pending_payout_value'], 'votes': response['net_votes'], 'comments': response['children'] } }) print('Updated post' + str(ids))
class UDPLikeWebSocketClient: def __init__(self, url) -> None: self.ws = WebSocket() self.url = url def try_to_connect(self): try: self.ws.connect(url=self.url) except ConnectionRefusedError: pass def try_to_send(self, d): try: self.ws.send(extend_dumps(d)) except BrokenPipeError: self.ws.close() def silent_send(self, channel, msg): if not self.ws.connected: self.try_to_connect() if not self.ws.connected: return self.try_to_send(dict(msg=msg, channel=channel))
def test_websocket(app: Flask, aio: AioHTTP): """Test for websocket""" @app.route('/echo') @websocket def echo(): while True: msg = yield from aio.ws.receive_msg() if msg.tp == aiohttp.MsgType.text: aio.ws.send_str(msg.data) elif msg.tp == aiohttp.MsgType.close: break elif msg.tp == aiohttp.MsgType.error: break with Server(app, aio) as server: ws = WebSocket() ws.connect(server.ws_url('/echo')) try: ws.send('foo') assert 'foo' == ws.recv() finally: ws.close()
def main(addr): """ Get gluware version with websocket :param addr: ip address of host (str) :return: version (str) """ # Turn off SSL certificate checking ssl_cert_off = {"cert_reqs": CERT_NONE} 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: return except Exception: return ws.send( '421["request",{"service":"DocsService","method":"getVersion","payload":{}}]' ) while True: message = ws.recv() if not 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_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 new_socket(domain=None, port=default_socket_port, headers={}, **kwargs): if envs.TENSORCI_SOCKET_URL: url = envs.TENSORCI_SOCKET_URL else: use_secure_sockets = kwargs.get('secure_sockets') is True or domain != 'localhost' if use_secure_sockets: protocol = 'wss://' port = 443 else: protocol = 'ws://' url = '{}{}:{}'.format(protocol, domain, port) formatted_headers = ['{}: {}'.format(k, v) for k, v in headers.items()] connect_kwargs = {} if formatted_headers: connect_kwargs['header'] = formatted_headers ws = WebSocket(**kwargs) ws.connect(url, **connect_kwargs) return ws
print " url: ", page.get('url', '') print " ws_debug_url: ", page.get('webSocketDebuggerUrl', '') sys.exit(1) page = sys.argv[1] print "Attempting to open page: %s on localhost:%s" % (page, debug_port) ws = WebSocket() # if ipv6 if 0: ws.io_sock = ws.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) #ws.connect("ws://localhost:9999/devtools/page/1") ws_url = "ws://localhost:%s/devtools/page/%s" % (debug_port, page) ws.connect(ws_url) counter = 0 def send(method, params): global counter counter += 1 # separators is important, you'll get "Message should be in JSON format." otherwise message = json.dumps({"id": counter, "method": method, "params": params}, separators=(',', ':')) print "> %s" % (message,) ws.send(message) def recv(): result = ws.recv() print "< %s" % (result,)
class WSClient: 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 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) self.sock.connect(url, header=header) self._connected = True def peek_channel(self, channel, timeout=0): """Peek a channel and return part of the input, empty string otherwise.""" self.update(timeout=timeout) if channel in self._channels: return self._channels[channel] return "" def read_channel(self, channel, timeout=0): """Read data from a channel.""" if channel not in self._channels: ret = self.peek_channel(channel, timeout) else: ret = self._channels[channel] if channel in self._channels: del self._channels[channel] return ret def readline_channel(self, channel, timeout=None): """Read a line from a channel.""" if timeout is None: timeout = float("inf") start = time.time() while self.is_open() and time.time() - start < timeout: if channel in self._channels: data = self._channels[channel] if "\n" in data: index = data.find("\n") ret = data[:index] data = data[index+1:] if data: self._channels[channel] = data else: del self._channels[channel] return ret self.update(timeout=(timeout - time.time() + start)) def write_channel(self, channel, data): """Write data to a channel.""" self.sock.send(chr(channel) + data) def peek_stdout(self, timeout=0): """Same as peek_channel with channel=1.""" return self.peek_channel(STDOUT_CHANNEL, timeout=timeout) def read_stdout(self, timeout=None): """Same as read_channel with channel=1.""" return self.read_channel(STDOUT_CHANNEL, timeout=timeout) def readline_stdout(self, timeout=None): """Same as readline_channel with channel=1.""" return self.readline_channel(STDOUT_CHANNEL, timeout=timeout) def peek_stderr(self, timeout=0): """Same as peek_channel with channel=2.""" return self.peek_channel(STDERR_CHANNEL, timeout=timeout) def read_stderr(self, timeout=None): """Same as read_channel with channel=2.""" return self.read_channel(STDERR_CHANNEL, timeout=timeout) def readline_stderr(self, timeout=None): """Same as readline_channel with channel=2.""" return self.readline_channel(STDERR_CHANNEL, timeout=timeout) def read_all(self): """Return buffered data received on stdout and stderr channels. This is useful for non-interactive call where a set of command passed to the API call and their result is needed after the call is concluded. Should be called after run_forever() or update() TODO: Maybe we can process this and return a more meaningful map with channels mapped for each input. """ out = self._all self._all = "" self._channels = {} return out def is_open(self): """True if the connection is still alive.""" return self._connected def write_stdin(self, data): """The same as write_channel with channel=0.""" self.write_channel(STDIN_CHANNEL, data) def update(self, timeout=0): """Update channel buffers with at most one complete frame of input.""" if not self.is_open(): return if not self.sock.connected: self._connected = False return r, _, _ = select.select( (self.sock.sock, ), (), (), timeout) if r: op_code, frame = self.sock.recv_data_frame(True) if op_code == ABNF.OPCODE_CLOSE: self._connected = False return elif op_code == ABNF.OPCODE_BINARY or op_code == ABNF.OPCODE_TEXT: data = frame.data if six.PY3: data = data.decode("utf-8") if len(data) > 1: channel = ord(data[0]) data = data[1:] if data: if channel in [STDOUT_CHANNEL, STDERR_CHANNEL]: # keeping all messages in the order they received for # non-blocking call. self._all += data if channel not in self._channels: self._channels[channel] = data else: self._channels[channel] += data def run_forever(self, timeout=None): """Wait till connection is closed or timeout reached. Buffer any input received during this time.""" if timeout: start = time.time() while self.is_open() and time.time() - start < timeout: self.update(timeout=(timeout - time.time() + start)) else: while self.is_open(): self.update(timeout=None) def close(self, **kwargs): """ close websocket connection. """ self._connected = False if self.sock: self.sock.close(**kwargs)
class WebSocketApp(object): """ Higher level of APIs are provided. The interface is like JavaScript WebSocket object. """ def __init__(self, url, on_open = None, on_message = None, on_error = None, on_close = None): """ 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.on_open = on_open self.on_message = on_message self.on_error = on_error self.on_close = on_close self.sock = None def send(self, data): """ send message. data must be utf-8 string or unicode. """ self.sock.send(data) def close(self): """ close websocket connection. """ self.sock.close() def run_forever(self): """ run event loop for WebSocket framework. This loop is infinite loop and is alive during websocket is available. """ if self.sock: raise WebSocketException("socket is already opened") try: self.sock = WebSocket() self.sock.connect(self.url) self._run_with_no_err(self.on_open) while True: data = self.sock.recv() if data is None: break self._run_with_no_err(self.on_message, data) except Exception, e: self._run_with_no_err(self.on_error, e) finally: