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?
js and Python finding out that Node. js is awesome for Web Development and Python for Data Sciences. Actually, we don't need to always stick with the same programming language as there are ways to use them both together. In this article, I will show you an example of how to use a Python script from the Node.
Node. js can maintain many hundreds of WebSockets connections simultaneously. WebSockets on the server can become complicated as the connection upgrade from HTTP to WebSockets requires handling. This is why developers commonly use a library to manage this for them.
websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With