Python websocket.create_connection() Examples

The following are 30 code examples of websocket.create_connection(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module websocket , or try the search function .
Example #1
Source File: test_max_websocket_uri_length.py    From unicorn-binance-websocket-api with MIT License 7 votes vote down vote up
def binance_test_uri_length(query):
    websocket = create_connection("wss://stream.binance.com:9443/stream?streams=" + query)
    while True:
        result = websocket.recv()
        websocket.close()
        print("Received '%s'\r\n" % result)
        break 
Example #2
Source File: vnhuobi.py    From vnpy_crypto with MIT License 7 votes vote down vote up
def reconnect(self):
        """重连"""
        try:
            if self.DEBUG:
                print('DataApi:reconnect:{}'.format(self.url))
            if not self.proxyHost:
                self.ws = create_connection(self.url)
            else:
                self.ws = create_connection(self.url, 
                                            http_proxy_host=self.proxyHost, 
                                            http_proxy_port=self.proxyPort)
            return True
        except:
            msg = traceback.format_exc()
            self.onError(u'行情服务器重连失败:%s' %msg)            
            return False
        
    #---------------------------------------------------------------------- 
Example #3
Source File: mopidy.py    From platypush with MIT License 6 votes vote down vote up
def _communicate(self, msg):
        import websocket

        if isinstance(msg, str):
            msg = json.loads(msg)

        self._msg_id += 1
        msg['jsonrpc'] = '2.0'
        msg['id'] = self._msg_id
        msg = json.dumps(msg)

        ws = websocket.create_connection(self.url)
        ws.send(msg)
        response = json.loads(ws.recv()).get('result')
        ws.close()
        return response 
Example #4
Source File: test_server.py    From qdb with Apache License 2.0 6 votes vote down vote up
def test_client_orphan_session(self):
        """
        Tests that a client makes it into the session store without a tracer
        attaching if attach_timeout is set to ALLOW_ORPHANS or 0.
        """
        with QdbServer(tracer_server=QdbNopServer(),
                       client_host='localhost',
                       client_port=0,
                       attach_timeout=ALLOW_ORPHANS) as server:
            client = create_connection(
                'ws://localhost:%d%s' % (server.client_server.server_port,
                                         DEFAULT_ROUTE_FMT.format(uuid='test'))
            )
            send_client_event(client, 'start', '')
            # yield to the session_store to let it get attached.
            gyield()
            self.assertIn('test', server.session_store) 
Example #5
Source File: test_server.py    From qdb with Apache License 2.0 6 votes vote down vote up
def test_tracer_orphan_session(self):
        """
        Tests that a tracer makes it into the session_store without a client
        attaching if attach_timeout is set to ALLOW_ORPHANS or 0.
        """
        with QdbServer(client_server=QdbNopServer(),
                       tracer_host='localhost',
                       tracer_port=0,
                       attach_timeout=ALLOW_ORPHANS) as server:
            tracer = gevent.socket.create_connection(
                ('localhost', server.tracer_server.server_port)
            )
            send_tracer_event(tracer, 'start', {
                'uuid': 'test',
                'auth': '',
                'local': (0, 0),
            })
            # yield to the session_store to let it get attached.
            gyield()
            self.assertIn('test', server.session_store) 
Example #6
Source File: generals.py    From generals-bot with MIT License 6 votes vote down vote up
def _connect_and_join(self, userid, username, mode, gameid, force_start, public_server):
		logging.debug("Creating connection")
		self._ws = create_connection(ENDPOINT_BOT if not public_server else ENDPOINT_PUBLIC)
		self._lock = threading.RLock()
		_spawn(self._start_sending_heartbeat)
		self._send(["set_username", userid, username, BOT_KEY])

		logging.info("Joining game")
		self._gameid = None
		if mode == "private":
			self._gameid = gameid
			if gameid is None:
				raise ValueError("Gameid must be provided for private games")
			self._send(["join_private", gameid, userid, BOT_KEY])
		elif mode == "1v1":
			self._send(["join_1v1", userid, BOT_KEY])
		elif mode == "team":
			self._send(["join_team", userid, BOT_KEY])
		elif mode == "ffa":
			self._send(["play", userid, BOT_KEY])
		else:
			raise ValueError("Invalid mode")

		if force_start:
			_spawn(self.send_forcestart) 
Example #7
Source File: test_server.py    From qdb with Apache License 2.0 6 votes vote down vote up
def test_tracer_auth_timeout(self):
        """
        Tests the auth timeout for new connections from the client.
        """
        with QdbServer(tracer_host='localhost',
                       tracer_port=0,
                       client_server=QdbNopServer(),
                       auth_timeout=1) as server:

            auth_failed_dict = fmt_err_msg('auth', 'No start event received')
            sck = gevent.socket.create_connection(
                ('localhost', server.tracer_server.server_port)
            )

            self.assertEqual(auth_failed_dict, recv_tracer_event(sck))
            self.assertFalse('test' in server.session_store) 
Example #8
Source File: test_server.py    From qdb with Apache License 2.0 6 votes vote down vote up
def test_bad_auth_tracer(self):
        """
        Tests a non-valid auth message for a tracer.
        """
        with QdbServer(tracer_host='localhost',
                       tracer_port=0,
                       tracer_auth_fn=lambda _: False,
                       client_server=QdbNopServer()) as server:

            auth_failed_dict = fmt_err_msg('auth', 'Authentication failed')

            sck = gevent.socket.create_connection(
                ('localhost', server.tracer_server.server_port)
            )

            send_tracer_event(sck, 'start', {
                'uuid': 'test',
                'auth': 'friendzoned-again',
                'local': (0, 0),
            })
            # We failed auth so the socket should be closed.
            self.assertEqual(auth_failed_dict,
                             recv_tracer_event(sck))
            self.assertFalse('test' in server.session_store) 
Example #9
Source File: test_server.py    From qdb with Apache License 2.0 6 votes vote down vote up
def test_client_auth_timeout(self):
        with QdbServer(client_host='localhost',
                       client_port=0,
                       auth_timeout=1,  # Timeout after 1 second.
                       tracer_server=QdbNopServer()) as server:
            ws = create_connection(
                'ws://localhost:%d%s' % (server.client_server.server_port,
                                         DEFAULT_ROUTE_FMT.format(uuid='test'))
            )

            auth_failed_dict = fmt_err_msg('auth', 'No start event received')
            disable_dict = fmt_msg('disable')

            auth_failed_msg = ''
            disable_msg = ''

            with gevent.Timeout(2, False):
                # The server should time us out in 1 second and send back these
                # two messages.
                auth_failed_msg = ws.recv()
                disable_msg = ws.recv()

            self.assertEquals(auth_failed_msg, json.dumps(auth_failed_dict))
            self.assertEquals(disable_msg, json.dumps(disable_dict))
            self.assertFalse('test' in server.session_store) 
Example #10
Source File: doc_retrieval_experiment_client.py    From combine-FEVER-NSMN with MIT License 6 votes vote down vote up
def find_sent_link_with_priority(cls, d_list, top_k=5, predict=False):
        ws_second = websocket.create_connection(cls.second_round_path)
        for i in spcl(range(len(d_list))):
            ws_second.send(json.dumps(d_list[i]))
            item = json.loads(ws_second.recv())
            pids = [it[0] for it in item['prioritized_docids']]
            item['prioritized_docids_aside'] = \
                [it for it in item['prioritized_docids_aside']\
                    if it[0] not in pids]
            if predict:
                porg = \
                    set([k for k, v \
                           in sorted(item['prioritized_docids'],
                                     key=lambda x: (-x[1], x[0]))][:top_k])
                paside = \
                    set([k for k, v \
                            in sorted(item['prioritized_docids_aside'],
                                      key=lambda x: (-x[1], x[0]))][:top_k])
                item['predicted_docids'] = list(porg | paside)
                item['predicted_docids_origin'] = list(porg)
                item['predicted_docids_aside'] = list(paside)
            d_list[i] = item
        ws_second.close() 
Example #11
Source File: hitbtc.py    From bitex with MIT License 6 votes vote down vote up
def _data_thread(self):
        try:
            conn = create_connection(self.addr)
        except Exception:
            self._controller_q.put('restart_data')
            return

        while self.running:
            try:
                data = conn.recv()
                data = json.loads(data)
            except WebSocketTimeoutException:
                self._controller_q.put('restart_data')
                return
            try:
                pair = data['MarketDataIncrementalRefresh']['symbol']
                endpoint = 'MarketDataIncrementalRefresh'
            except KeyError:
                pair = data['MarketDataSnapshotFullRefresh']['symbol']
                endpoint = 'MarketDataSnapshotFullRefresh'
            self.data_q.put((endpoint, pair, data[endpoint], time.time())) 
Example #12
Source File: hitbtc.py    From bitex with MIT License 6 votes vote down vote up
def _trade_thread(self):
        try:
            conn = create_connection(self.trader_addr)
        except Exception:
            log.exception('Trader Thread Error!')
            self._controller_q.put('restart_trader')
            return

        while self.running:
            try:
                data = conn.recv()
            except WebSocketTimeoutException:
                self._controller_q.put('restart_data')
                return
            self.data_q.put(json.loads(data))

            try:
                payload = self.trade_command_q.get()
            except Empty:
                continue

            try:
                conn.send(self.sign(payload))
            except (WebSocketTimeoutException, ConnectionResetError):
                continue 
Example #13
Source File: remote_websocket.py    From AlexaControlledSamsungTV with MIT License 6 votes vote down vote up
def __init__(self, config):
        import websocket
        self.token_file = os.path.dirname(os.path.realpath(__file__)) + "/" + config["mac_address"]
        if not config["port"]:
            config["port"] = 8001

        if "timeout" not in config or ("timeout" in config and config["timeout"] == 0):
            config["timeout"] = None

        if config["port"] == 8002:
            url = SSL_URL_FORMAT.format(config["host"], config["port"],
                                        self._serialize_string(config["name"]))
            if os.path.isfile(self.token_file):
                with open(self.token_file, "r") as token_file:
                    url += "&token=" + token_file.readline()
            else:
                config["timeout"] = 10
            self.connection = websocket.create_connection(url, config["timeout"], sslopt={"cert_reqs": ssl.CERT_NONE})

        else:
            url = URL_FORMAT.format(config["host"], config["port"],
                                    self._serialize_string(config["name"]))
            self.connection = websocket.create_connection(url, config["timeout"])
        self._read_response() 
Example #14
Source File: input.py    From tributary with Apache License 2.0 6 votes vote down vote up
def ws(url, callback, json=False, wrap=False):
    '''Connect to websocket and pipe results through the callback

    Args:
        url (str): websocket url to connect to
        callback (callable): function to call on websocket data
        json (bool): load websocket data as json
        wrap (bool): wrap result in a list
    '''
    ws = create_connection(url)
    for x in run(ws.recv):
        if isinstance(x, StreamNone):
            continue
        elif not x or isinstance(x, StreamEnd):
            break

        if json:
            x = load_json(x)
        if wrap:
            x = [x]
        callback(x) 
Example #15
Source File: kimotion.py    From BiblioPixelAnimations with MIT License 6 votes vote down vote up
def __init__(self, server):
        super().__init__()
        self.setDaemon(True)
        self._stop = threading.Event()
        self._reading = thread_lock()
        self.dt = np.dtype(np.uint16)
        self.dt = self.dt.newbyteorder('<')
        self._data = [np.zeros(WS_FRAME_SIZE, self.dt),
                      np.zeros(WS_FRAME_SIZE, self.dt)]
        self._buf = False
        self.ws = create_connection("ws://{}/".format(server)) 
Example #16
Source File: websocket_client.py    From networking-odl with Apache License 2.0 6 votes vote down vote up
def _socket_create_connection(self, stream_url):
        ws = None
        try:
            ws = websocket.create_connection(stream_url,
                                             timeout=self.timeout)
        except ValueError:
            with excutils.save_and_reraise_exception():
                LOG.error("websocket create connection invalid URL")
        except Exception:
            # Although a number of exceptions can occur here
            # we handle them all the same way, return None.
            # As such, enough to just "except Exception."
            LOG.exception("websocket create connection failed",
                          exc_info=True)
            return None
        if ws is None or not ws.connected:
            LOG.error("websocket create connection unsuccessful")
            return None

        LOG.debug("websocket connection established")
        return ws 
Example #17
Source File: websocket.py    From sgqlc with ISC License 6 votes vote down vote up
def __init__(self, url, connection_payload=None, **ws_options):
        '''
        :param url: ws:// or wss:// url to connect to
        :type url: str

        :param connection_payload: data to pass during initiation of the
          WebSocket connection. It's passed as ``"payload"`` key of the
          ``connection_init`` type message.
        :type connection_payload: dict

        :param ws_options: options to pass to websocket.create_connection
        :type ws_options: dict
        '''
        self.url = url
        self.connection_payload = connection_payload
        self.ws_options = ws_options
        self.keep_alives = ['ka'] 
Example #18
Source File: websocket_win.py    From jdcloud-cli with Apache License 2.0 5 votes vote down vote up
def invoke_shell(self, url, header):
        shell = websocket.create_connection(url, timeout=10, header=header)
        shell.send_binary('\n')

        threading.Thread(target=show_response, args=(shell,)).start()
        try:
            while True:
                x = msvcrt.getch()
                shell.send_binary(x)
        except websocket.WebSocketConnectionClosedException as e:
            print(e.message)
        except websocket.WebSocketException as e:
            print(e.message) 
Example #19
Source File: doc_retrieval_experiment_client.py    From combine-FEVER-NSMN with MIT License 5 votes vote down vote up
def sample_answer_with_priority(cls, d_list, top_k=5):
        ws_first = websocket.create_connection(cls.first_round_path)

        for i in spcl(range(len(d_list))):
        # for i in spcl(range(10)):
            ws_first.send(json.dumps(d_list[i]))
            item = json.loads(ws_first.recv())
            item['predicted_docids'] = \
                list(set([k for k, v \
                            in sorted(item['prioritized_docids'],
                                      key=lambda x: (-x[1], x[0]))][:top_k]))
            d_list[i] = item
        ws_first.close() 
Example #20
Source File: okcoin.py    From bitex with MIT License 5 votes vote down vote up
def _process_data(self):
        self.conn = create_connection(self.addr, timeout=4)
        for pair in self.pairs:
            payload = [{'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_ticker' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_depth_60' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_trades' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_kline_1min' % pair}]
            log.debug(payload)
            self.conn.send(json.dumps(payload))
        while self.running:
            try:
                data = json.loads(self.conn.recv())
            except (WebSocketTimeoutException, ConnectionResetError):
                self._controller_q.put('restart')

            if 'data' in data:
                pair = ''.join(data['channel'].split('spot')[1].split('_')[:2]).upper()
                self.data_q.put((data['channel'], pair, data['data'],
                                 time.time()))
            else:
                log.debug(data)
        self.conn = None 
Example #21
Source File: gdax.py    From bitex with MIT License 5 votes vote down vote up
def _process_data(self):
        self.conn = create_connection(self.addr, timeout=4)
        payload = json.dumps({'type': 'subscribe', 'product_ids': self.pairs})
        self.conn.send(payload)
        while self.running:
            try:
                data = json.loads(self.conn.recv())
            except (WebSocketTimeoutException, ConnectionResetError):
                self._controller_q.put('restart')

            if 'product_id' in data:
                self.data_q.put(('order_book', data['product_id'],
                                 data, time.time()))
        self.conn = None 
Example #22
Source File: screenrecord.py    From uiautomator2 with MIT License 5 votes vote down vote up
def _iter_minicap(self):
        http_url = self._d.path2url("/minicap")
        ws_url = re.sub("^http", "ws", http_url)
        ws = create_connection(ws_url)
        try:
            while not self._stop_event.is_set():
                msg = ws.recv()
                if isinstance(msg, str):
                    # print("<-", msg)
                    pass
                else:
                    yield msg
        finally:
            ws.close() 
Example #23
Source File: remote.py    From samsung-tv-api with MIT License 5 votes vote down vote up
def __init__(self, host, port=8001, name='SamsungTvRemote'):
        self.connection = websocket.create_connection(
            self._URL_FORMAT.format(**{
                'host': host, 
                'port': port, 
                'name': self._serialize_string(name)
            })
        )

        response = json.loads(self.connection.recv())
        if response['event'] != 'ms.channel.connect':
            self.close()
            raise Exception(response) 
Example #24
Source File: test_server.py    From qdb with Apache License 2.0 5 votes vote down vote up
def test_tracer_attach_timeout(self, mode):
        """
        Tests the case where a tracer attaches but no client does.
        """
        with QdbServer(tracer_host='localhost',
                       tracer_port=0,
                       client_server=QdbNopServer(),
                       attach_timeout=0.01,
                       timeout_disable_mode=mode) as server:

            tracer = gevent.socket.create_connection(
                ('localhost', server.tracer_server.server_port)
            )
            send_tracer_event(tracer, 'start', {
                'uuid': 'test',
                'auth': '',
                'local': (0, 0),
            })
            disable_event = None
            with gevent.Timeout(0.1, False):
                error_event = recv_tracer_event(tracer)
                disable_event = recv_tracer_event(tracer)

            error_dict = fmt_err_msg('client', 'No client')

            self.assertEqual(error_dict, error_event)
            self.assertEqual(fmt_msg('disable', mode), disable_event)
            self.assertNotIn('test', server.session_store) 
Example #25
Source File: test_server.py    From qdb with Apache License 2.0 5 votes vote down vote up
def test_inactivity_timeout(self, mode):
        """
        Tests that timeout sends a disable message with the proper mode..
        """
        with QdbServer(tracer_host='localhost',
                       tracer_port=0,
                       client_host='localhost',
                       client_port=0,
                       inactivity_timeout=0.01,  # minutes
                       sweep_time=0.01,  # seconds
                       timeout_disable_mode=mode) as server:

            tracer = gevent.socket.create_connection(
                ('localhost', server.tracer_server.server_port)
            )
            send_tracer_event(tracer, 'start', {
                'uuid': 'test',
                'auth': '',
                'local': (0, 0),
            })
            client = create_connection(
                'ws://localhost:%d%s' % (server.client_server.server_port,
                                         DEFAULT_ROUTE_FMT.format(uuid='test'))
            )
            send_client_event(client, 'start', '')
            self.assertEqual({'e': 'start', 'p': ''},
                             recv_tracer_event(tracer))
            self.assertEqual({'e': 'disable', 'p': mode},
                             recv_tracer_event(tracer))
            self.assertEqual('disable', recv_client_event(client)['e'])
            self.assertFalse('test' in server.session_store) 
Example #26
Source File: test_server.py    From qdb with Apache License 2.0 5 votes vote down vote up
def test_bad_auth_client(self):
        """
        Tests a non-valid auth message for a client.
        """
        with QdbServer(client_host='localhost',
                       client_port=0,
                       client_auth_fn=lambda _: False,  # Fail all new clients.
                       tracer_server=QdbNopServer()) as server:

            ws = create_connection(
                'ws://localhost:%d%s' % (server.client_server.server_port,
                                         DEFAULT_ROUTE_FMT.format(uuid='test'))
            )
            send_client_event(ws, 'start', 'friendzoned-again')

            auth_failed_event = disable_event = None

            with gevent.Timeout(2, False):
                # The server should time us out in 1 second and send back these
                # two messages.
                auth_failed_event = recv_client_event(ws)
                disable_event = recv_client_event(ws)

            auth_failed_dict = fmt_err_msg('auth', 'Authentication failed')

            self.assertEquals(auth_failed_event, auth_failed_dict)
            self.assertEquals(disable_event['e'], 'disable')
            self.assertFalse('test' in server.session_store) 
Example #27
Source File: __init__.py    From pebble-linux-remote with GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
        try:
            self.ws = websocket.create_connection(self.url)
        except (websocket.WebSocketException, socket.error) as e:
            raise ConnectionError(str(e)) 
Example #28
Source File: predix.py    From thingflow-python with Apache License 2.0 5 votes vote down vote up
def _send(self):
        if self.ws is None:
            logging.info("Connecting to Predix...")
            self.ws = create_connection(self.ingest_url, header=self.headers)
            logging.info("Connected")
        body = json.dumps(_create_ingest_body(self.pending_events, extractor=self.extractor))
        #print(body)
        self.ws.send(body)
        result = self.ws.recv()
        rdata = json.loads(result)
        if rdata['statusCode']!=202:
            raise PredixError("Unexpected websocket response: %s" % result)
        self.pending_events = [] 
Example #29
Source File: doc_retrieval_experiment_client.py    From combine-FEVER-NSMN with MIT License 5 votes vote down vote up
def feed_sent_file(cls, path):
        """Use absolute path, and it should appear in my repo"""
        ws_feed = websocket.create_connection(cls.feed_path)
        ws_feed.send(path)
        return_msg = ws_feed.recv()
        print(return_msg)
        ws_feed.close() 
Example #30
Source File: websocket_client.py    From wrapanapi with MIT License 5 votes vote down vote up
def connect(self):
        """connects with the initialized detail"""
        if self.ws and self.ws.connected:
            return self.ws
        else:
            websocket.enableTrace(self.enable_trace)
            if self.username:
                base64_creds = base64.b64encode("{}:{}".format(self.username, self.password))
                self.headers.update({"Authorization": "Basic {}".format(base64_creds)})
            self.ws = websocket.create_connection(self.url, header=self.headers)
            self.ws.settimeout(self.timeout)