def connect_web_socket(self): config = self._controller.config if 'secure_server' in config: secure_server = config.secure_server else: host_name = config.server_name.split(':')[0] secure_server = host_name != 'localhost' and host_name != '127.0.0.1' protocol = 'wss' if secure_server else 'ws' if config.get('old_auth', False): headers = None else: user_name = self._controller.VERSION + '.' + self._controller.BUILD # send client version as user name password = config.secret_key # send secret key as password headers = [('Authorization', 'Basic %s' % base64.b64encode( ('%s:%s' % (user_name, password)).encode()).decode())] ws = WebSocketClient(protocol + '://' + config.server_name + '/api/v1/websocket', protocols=['http-only'], headers=headers) try: ws.connect() logging.debug('opened websocket connection to server') except Exception as e: logging.debug(str(e)) logging.warning('error connecting to websocket server') ws = None return ws
def connect(host, port, path='/'): try: try: ws = WebSocketClient("ws://{}:{}{}".format(host, port, path)) ws.connect() def outgoing(): fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) while True: wait_read(sys.stdin.fileno()) line = sys.stdin.readline() ws.send(line.strip()) def incoming(): while True: print ws.receive() gevent.joinall([ gevent.spawn(outgoing), gevent.spawn(incoming), ]) except (IOError, HandshakeError), e: print e sys.exit(1) except KeyboardInterrupt: ws.close()
def connect(self, url): if self.__connected == True: raise RuntimeError("Connect twice") self.__connection = WebSocketClient(url) self.__connection.connect() #self.__connected = True if self.__on_message is not None: self.__pool.spawn(self.__on_message) self.__connected == True
def test_secure_websocket_connection(self): ws = WebSocketClient('wss://127.0.0.1:5443/ws') ws.connect() print("Sending: 'Hello, World'...") ws.send("Hello, World") print("Sent") print("Receiving...") result = ws.receive() print("Received: {}".format(result)) ws.close() self.assertEqual("Hello, World", str(result))
def publish(self, data, parsed_data): payload = parsed_data parsed = json.dumps(payload) evald = payload try: ws = WebSocketClient(socket_config['baseUrl'] + str(evald['pipelineId']), protocols=['http-only', 'chat']) ws.connect() ws.send(str(parsed)) ws.close() return True except Exception as e: print e return False
def proxy(url): with app.test_request_context(): if websocket: while True: data = websocket.receive() websocket_url = 'ws://{}/{}'.format(PROXY_DOMAIN, url) if websocket_url not in websockets: client = WebSocketClient(websocket_url, protocols=['http-only', 'chat']) websockets[websocket_url] = client else: client = websockets[websocket_url] client.connect() if data: client.send(data) client_data = client.receive() if client_data: websocket.send(client_data) return Response() if request.method == "GET": url_ending = "%s?%s" % (url, request.query_string) url = PROXY_FORMAT % url_ending resp = requests.get(url) elif request.method == "POST": if url == 'kernels': url_ending = "%s?%s" % (url, request.query_string) url = PROXY_FORMAT % url_ending else: url = PROXY_FORMAT % url resp = requests.post(url, request.data) else: url = PROXY_FORMAT % url resp = requests.request(url, request.method, request.data) content = resp.content if content: content = PROXY_REWRITE_REGEX.sub(r'\1/proxy/', content) headers = resp.headers if "content-type" in headers: mimetype = headers["content-type"].split(";")[0].split(",")[0] else: mimetype = None response = Response(content, headers=dict(headers), mimetype=mimetype, status=resp.status_code) return response
def webSocketReconnect(self): """ WSock.receive sometimes hangs, as in the case of a disconnect Receive blocks, but send does not, so we use send as a tester An ideal connection will have a 1:1 ratio of send and receive However, bad connections will have poorer ratios such as 10:1 If ratio reaches 20:1 then this function will force reconnect This function is triggered when CLIENT_LATEST_CLIP is set, but SERVER_LATEST_CLIP is not, and the outgoing loop keeps calling """ while 1: if self.KEEP_RUNNING: try: self.wsock.close_connection( ) # Terminate Nones the environ and stream attributes, which is for servers except AttributeError: pass try: self.last_sent = self.last_alive = datetime.datetime.now() login = self._notify_window.getLogin() self.wsock = WebSocketClient( URL( "ws", DEFAULT_DOMAIN, DEFAULT_PORT, "ws", email=login.get("email") or "", password=login.get("password" or ""), ) ) #email="*****@*****.**", password="******" #keep static to guarantee one socket for all instances self.wsock.connect() break except (SocketError, exc.HandshakeError, RuntimeError): print "no connection..." self._notify_window.destroyBusyDialog() self._notify_window.sb.toggleStatusIcon( msg="Unable to connect to the internet.", icon="bad") gevent.sleep(1)
def __init__(self, local_port, name, broker_address): self.local_port = local_port self.ws = WebSocketClient('http://%s/t/%s' % (broker_address, name)) self.connections = {} self._send_lock = Semaphore()
def writeToWavFileFromMic(p, frames): # create a wav file from captured data wf = wave.open("test.wav", 'wb') wf.setnchannels(cw.channels_mic) wf.setsampwidth(p.get_sample_size(cw.sampling_format)) wf.setframerate(cw.sampling_rate_mic) wf.writeframes(b''.join(frames)) wf.close() if __name__ == '__main__': ap = argparse.ArgumentParser(usage="python ClientWolf.py --mode file/mic") ap.add_argument('-m', '--mode', default="file", required=True, help='From where to take input data ? Can be file/mic') args = ap.parse_args() ws = WebSocketClient('ws://%s:%i/ws' % (cw.ws_server_host,cw.ws_server_port), protocols=['http-only', 'chat']) ws.connect() logging.info("Client connected to server.") print('------Client Started at %s--------' % (time.time())) def close_connection(): ws.close(reason="user_terminated_action") ws.close_connection() def incoming(): i = 0 op_buffer = {} end_not_received = True while end_not_received: m = ws.receive(block=True) msg = str(m)
def do_open(self): url = self.uri() self.websocket = WebSocketClient(url) self.websocket.connect() self.on_open() self.read_job = gevent.spawn(self._read)
import gevent from ws4py.client.geventclient import WebSocketClient ws = WebSocketClient('wss://real.okex.com:10441/websocket', protocols=['http-only', 'chat']) ws.connect() def incoming(): """ Greenlet waiting for incoming messages until ``None`` is received, indicating we can leave the loop. """ while True: print('incoming') m = ws.receive() if m is not None: print(m) else: break def send_a_bunch(): print('send_a_bunch') ws.send("{'event':'addChannel','channel':'ok_sub_spot_etc_btc_depth_5'}") print('dsfffffff') greenlets = [ gevent.spawn(send_a_bunch), gevent.spawn(incoming),
#!/usr/bin/python #coding=utf-8 from gevent import monkey monkey.patch_all(select=False) import gevent from ws4py.client.geventclient import WebSocketClient ws = WebSocketClient('ws://ws.vnbig.com/ws', protocols=['http-only', 'chat']) ws.connect() def reqParam(): coin = [ '_eth_ltc', '_usdt_csi', '_btc_csi', '_eth_eos', '_usdt_ltc', '_eth_bch', '_btc_eos', '_eth_csi', '_usdt_btc', '_btc_bch', '_btc_etc', '_btc_eth', '_btc_ltc', '_usdt_bch', '_usdt_eth' ] period = [ '_1min', '_5min', '_15min', '_30min', '_1hour', '_4hour', '_6hour', '_12hour', '_1day', '_1week', '_1month' ] list_param = [] for i in coin: for j in period: list_param.append( "{'event':'addChannel','channel':'vnbig%s%s_ticker'}" % (i, j)) list_param.append("{'event':'addChannel','channel':'vnbig%s_depth'}" % i) list_param.append("{'event':'addChannel','channel':'vnbig%s_trade'}" %
# -*- coding: utf-8 -*- from gevent import monkey; monkey.patch_all() import gevent from ws4py.client.geventclient import WebSocketClient if __name__ == '__main__': ws = WebSocketClient('ws://127.0.0.1:9000/ws', protocols=['http-only', 'chat']) ws.connect() ws.send("Hello world") print((ws.receive(),)) ws.send("Hello world again") print((ws.receive(),)) def incoming(): while True: m = ws.receive() if m is not None: m = str(m) print((m, len(m))) if len(m) == 35: ws.close() break else: break print(("Connection closed!",)) def outgoing(): for i in range(0, 40, 5):
# -*- coding: utf-8 -*- from gevent import monkey monkey.patch_all() import gevent from ws4py.client.geventclient import WebSocketClient if __name__ == '__main__': ws = WebSocketClient('ws://localhost:9000/ws', protocols=['http-only', 'chat']) ws.connect() ws.send("Hello world") print((ws.receive(), )) ws.send("Hello world again") print((ws.receive(), )) def incoming(): while True: m = ws.receive() if m is not None: m = str(m) print((m, len(m))) if len(m) == 35: ws.close() break else: break print(("Connection closed!", ))
def handle(self, source, address): ''' 1. parse browser socks5 message 2. establishes WebSocket connection to a remote server 3. encrypt data using RC4 4. forward with both the local and remote server ''' log('New connection from %s:%s' % address) log('greenlet is %r', gevent.getcurrent()) rfile = source.makefile('rb', -1) try: recvcount = source.recv(262) log("recv count: %r: %r " % (recvcount, type(recvcount))) source.send(b'\x05\x00') wsdata = '' data = rfile.read(4) log('second pack %r: %r' % (type(data), data)) cmd = ord(data[1]) # CMD addrtype = ord(data[3]) # ADDR type 0x01 Ipv4 address wsdata = data[3] # append type of address if addrtype == 1: # IPv4 addrStr = rfile.read(4) addr = socket.inet_ntoa(addrStr) wsdata += addrStr elif addrtype == 3: # Domain name domainlen = ord(rfile.read(1)[0]) domain = rfile.read(domainlen) log('domain len and name: %d %s' % (domainlen, domain)) # addr = handle_dns(domain) addr = socket.inet_ntoa('\x00\x00\x00\x00') # 16777343 wsdata += chr(domainlen) wsdata += domain portstr = rfile.read(2) port = struct.unpack('>H', portstr) wsdata += portstr # append port if cmd == 1: reply = b"\x05\x00\x00\x01" + socket.inet_aton( addr) + struct.pack(">H", port[0]) log("send replay %r" % reply) source.send(reply) log('Begin data, %s:%s' % (addr, port[0])) ws = WebSocketClient(self.remotehost, protocols=['binary']) try: # gevent.monkey 阻塞 ws.connect() log("connect remote websocket server!") log('send data %r:%r:%r' % (wsdata, type(wsdata), len(wsdata))) encryptor = RC4(self.key) generator = encryptor.encrypter() out = '' for wc in wsdata: out += chr((ord(wc) ^ generator.next())) # send socks5 message ws.send(out, True) l1 = gevent.spawn(self.forward, source, ws, generator) l2 = gevent.spawn(self.incoming, ws, source) gevent.joinall([l1, l2]) except socket.error as e: log('Conn refused, %s:%s:%s' % (addr, port[0], e.message)) # Connection refused reply = b'\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00' source.send(reply) raise e finally: log('close websocket: ---------------------------') ws.close() else: log('Unsupported cmd: %r' % cmd) reply = b"\x05\0x07\0x00\0x01" source.send(reply) except socket.error, (value, message): log('socks_handle socket error, %s' % (message))