Skip to content Skip to sidebar Skip to footer

Connect Javascript Client To Python Websocket Server

I have this working python websocket server: #!/usr/bin/env python from socket import * HOST = '' PORT = 8080 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_

Solution 1:

The Python socket module doesn't have anything to do with websockets.

WebSocket, like HTTP, is a protocol implemented on top of an underlying transport. What your code does is setup a TCP server listening on port 8080. Websockets are a layer above that, just like HTTP. You can see the browser attempt to handshake with your server but it gives up because your server doesn't respond appropriately.

The websocket protocol is somewhat complicated and you'll probably want a library to handle it for you. One example is the websockets module:

#!/usr/bin/env pythonimport asyncio
import websockets

asyncdefecho(websocket, path):
    asyncfor message in websocket:
        await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()

Post a Comment for "Connect Javascript Client To Python Websocket Server"