Is there any way to connect Python to a Websocket as if it were a client?

3

Modern browsers have the Websocket object, which allows you to connect to a Websocket server, allowing real-time communication.

My question is:

  • Is there a library in Python that would allow me to connect to a Websocket, receiving and sending the data as if it were the browser?
  • If not, can you make an implementation that allows me to connect to a WebSocket server?
asked by anonymous 17.08.2018 / 16:10

2 answers

3

Yes, there is (there should be more, maybe list later):

Install via pip:

pip install websocket-client

An example usage provided:

  

Note: ws://echo.websocket.org/ is a test service

import websocket

try:
    import thread
except ImportError:
    import _thread as thread

import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Just to include a detail of the code, I think this is for compatibility between Python2.7 and Python3:

try:
    import thread #python2, se falhar vai para o except
except ImportError:
    import _thread as thread #python3 para python3
  

If not, is it possible to make an implementation that allows me to connect to a WebSocket server?

If a lib can do this then yes, it is possible to manually do this process, as soon as possible you write explaining about the handshake so you can give an explanation of how to create your own "client" for WebSockets.

  

Response under construction ...

    
17.08.2018 / 17:42
1

I suggest using aiohttp because it is asynchronous and thus does not need threads:

async with session.ws_connect('ws://echo.websocket.org') as ws:
    await ws.send_str('Olá Websocket!')
    async for msg in ws:
        print('Recebi', msg.type, msg.data)
        if msg.type == aiohttp.WSMsgType.TEXT:
            if msg.data == 'Olá Websocket!':
                await ws.close()
                break
            else:
                await ws.send_str(msg.data + '/answer')
        elif msg.type == aiohttp.WSMsgType.ERROR:
            break
    
17.08.2018 / 19:40