perennial_
perennial_

Reputation: 1846

Communicate Between Nodejs and Python via Websockets

I'm trying to send data from python to nodejs via websockets.

Js:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

server.listen(3000, () => console.log('running on 3000'));

io.sockets.on('connection', function(socket) {
    io.sockets.on('msg', function(data) {
        console.log(data);
    });
});

Python:

import asyncio
import websockets

async def sendData(uri, data):
    // FAILS ON THE FOLLOWING LINE:
    async with websockets.connect(uri) as websocket:
        await websocket.send(json.dumps(data))

def main():
    text = "sample data"
    asyncio.get_event_loop().run_until_complete(
        sendData("ws://localhost:3000", {"msg": text})
    )

main()

I'm getting "Malformed HTTP message" errors (websockets.exceptions.InvalidMessage: Malformed HTTP message) I'm concerned python websockets may not be designed to interface with socket.io. Thoughts?

Upvotes: 8

Views: 3368

Answers (1)

jfriend00
jfriend00

Reputation: 708166

A socket.io server can only communicate with a socket.io client. It cannot communicate with a plain webSocket client.

Socket.io adds it's own data format and connection scheme on top of webSocket and its server expects that data format and connection scheme to be there in order to even allow an initial connection.

So, you can't use a webSocket client to connect to a socket.io server.

Your options here are to either get a socket.io client library for Python or change your server to just a plain webSocket server.

Upvotes: 14

Related Questions