I've got a simple nodejs server that runs socketio and I can do 2 way communication with the client from the HTML. Now I'm also trying to connect to the same nodejs websocket from a Python script, but not getting connected.
Simplified Node JS webserver:
var http = require('http').createServer(handler);
var fs = require('fs');
var io = require('socket.io')(http)
http.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/public/index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}
io.sockets.on('connection', function (socket) {
setInterval(() => {
socket.emit('temp', 'tempfromserver')
}, 1000)
});
The Python script that wants to connect to the nodejs with websocket:
import socketio
sio = socketio.Client();
sio.connect('http://localhost:8080')
#sio.event
def message(data):
print('received message')
def connect():
print('socketio connected')
Is it possible to connect with a websocket via socketio to the nodejs server? If so, what am I doing wrong?
End goal is to collect sensor data from python script on raspberry pi and send to nodejs server which in its turn saves it to DB and sends through to HTMl client. Perhaps there is a better setup to do this.
I believe I asked a similar question and got an answer. My setup was a little different, and used a web-socket, but it will at least allow you to connect between Node JS and Python, and then maybe you can build from there, Using Socket IO and aiohttp for data transfer between node JS and Python. The setup was also originally based off a html script on the node JS side, so that may help as well in comparing it to your setup.
Related
There must be a simple mistake in my understanding of reactjs or socket.io. I have a server that sends "speed" values iterating from 2 to 5, and a client that receives them and displays them.
The issue:
Expected behavior: client displays numbers iterating from 1 to 5 every second and stops at 5. Client logs that it has received 4 messages with updated speed value (a new message every second)
Actual behavior: client displays a speed of 1. Client waits 4 seconds. Client displays a speed of 5 and, in that moment, logs having received the 4 messages with iterating speed from the server.
What is the issue? It's almost as if the server is sending all 4 speed messages at the same time.
Client code:
import React from 'react';
import {CircleGauge} from 'react-launch-gauge';
import io from 'socket.io-client';
class App extends React.Component {
constructor(props, context) {
super(props, context)
this.state = {
speed: 1
};
}
componentDidMount() {
const socket = io('http://localhost:5000');
socket.on('data update', data =>
this.setState( { speed: data },
() => console.log("got the speed: " + this.state.speed)));
socket.open();
}
render() {
return (
<div>
<p> The velocity received is: {this.state.speed} </p>
</div>
);
}
}
export default App;
Server Code:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import time
sendData = False;
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on('connect')
def dataSent():
print('they connected**********************************')
for i in range(2,6):
socketio.emit('data update', i)
time.sleep(1)
print(i)
if __name__ == '__main__':
socketio.run(app, debug = True)
When the client requests the websocket connection via
const socket = io(‘ws://localhost:5000’);
it will have to wait until the connection is established first, before it can do anything with the message. The connection is established only when
#socketio.on(‘connect’)
def ...
is finished. So it looks like the client waits until all the emit is done, and then start reacting to the messages.
You probably need to make your for-loop asynchronous so that the server responds to the client about the connection first before it emits the data. For example, you can carve out the for-loop into a separate function and use flask’s background task:
#socketio.on(‘connect’)
def dataSent():
print(‘...’)
socketio.start_background_task(target=emitloop)
def emitloop():
for i in range(2,6):
socketio.emit(‘data update’, i)
time.sleep(1)
(If flask is configured to use gevent for the background task, then you’ll need to install gevent or flask’s gevent plug-in.)
You might also try to use function based setState (i.e. passing a function to setState rather than the state object), because setState is asynchronous and react can combine them together otherwise.
I need a bit of help.
I'm doing tests to learn how to build a realtime web, so I use node.js with socket.io. All works fun but if I try to publish some message in the channel that is listening node with a different source that isn't node or javascript it crashes.
Server side: (node that fails when a external publish is sended)
var app = require('express')();
var http = require('http').Server(app);
var pub = require('redis').createClient(6379, 'localhost', {detect_buffers: true, return_buffers: false});
var sub = require('redis').createClient(6379, 'localhost', {return_buffers: true});
var io = require('socket.io')(http);
var redis = require('socket.io-redis');
io.adapter(redis({pubClient: pub, subClient: sub, host: '127.0.0.1', port: 6379}));
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log("something happens: " + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You don't need the client-side code for try it, just put this code and run it with node. When it is running, try to publish on the channel with Redis directly and see whats happens.
Error: 5 trailing bytes
at Object.decode (.../node/node_modules/msgpack-js-v5/msgpack.js:266:47)
at Redis.onmessage (.../node/node_modules/socket.io-redis/index.js:93:24)
at emitTwo (events.js:87:13)
at RedisClient.emit (events.js:172:7)
at RedisClient.return_reply (.../node/node_modules/redis/index.js:654:22)
at .../node/node_modules/redis/index.js:307:18
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
enter code here
Somebody understands why this happen? How can I fix it?
Thank you!
NEW COMMENT:
Thanks to robertklep I know that it need to use the same protocol, so I wrote a simple Python script using it, but it fails with the same error.
import redis
import msgpack
text_packed = msgpack.packb('refresh', use_bin_type=True)
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.publish('socket.io#/#', text_packed)
I also tried this approach, I think Im passing some param wrong:
from emitter import Emitter
io = Emitter(dict(host='localhost', port=6379))
io.Emit('chat message', "message from python!")
# or specificating the room
io.To("socket.io#/#").Emit('chat message', "message from python!")
In this case, nothing arrives to redis.
socket.io-redis uses msgpack on top of Redis to pub/sub messages, so you can't just push regular strings to it and expect it to work. The client you're using needs to be talking the same protocol.
I have a Python server using Flask, that has a websocket connection using Flask-SocketIO . There is a similar question :
Send custom data along with handshakeData in socket.io? The idea is to do the same thing but instead of using Node, using Flask. I want the client to send some data in the connect event, for example:
var socket = io("http://127.0.0.1:3000/", { query: "foo=bar" });
I haven't been able to get that custom data, and I can't rely on cookies due to the client's framework. A working solution is to have the connect event as usual, and then, in a custom event, get that information as a payload. But what we would want is to only have to do a connect event. Thanks!
As Miguel suggested in his comment you can simply do
from flask import Flask
from flask import request
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on('connect')
def connect():
foo = request.args.get('foo')
# foo will be 'bar' when a client connects
socketio.run(app)
on the server side.
The global connect method gets called on server side. But not my connect method for a specific namespace. Are namespaces supporting query parameter?
Client Code
const socket = io.connect('http://127.0.0.1:5000/ds', { query: {name: "Test"} });
Server Code
#socketio.on('connect', namespace='/ds')
def test_connect():
foo = request.args.get('foo')
print("CONNECT DS")
as of this time in 2021 you can send Auth data from python-socketio client with
sio.connect('http://localhost:6000/',auth={"authToken":"some auth token"})
I'm basically building a visual trace route application. The trace route is basically done using a python code and the results are send to the HTML page in real time using web socket. I basically need to do long polling( the server receives one request, process it and sent a maximum of 30 replies to each client at regular or irregular intervals), as well as handle multiple clients. I basically manipulated the below code to work for my application. I found the code from Asynchronous Bottle Framework
from bottle import request, Bottle, abort
app = Bottle()
#app.route('/websocket')
def handle_websocket():
wsock = request.environ.get('wsgi.websocket')
if not wsock:
abort(400, 'Expected WebSocket request.')
while True:
try:
message = wsock.receive()
wsock.send("Your message was: %r" % message)
except WebSocketError:
break
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError
server = WSGIServer(("0.0.0.0", 8080), app,
handler_class=WebSocketHandler)
server.serve_forever()
It does work on a single request. When I issue the second one.. 'wsock.send()' fails... it shows socket dead error. Could someone guide me on, how to handle multiple clients as well. Like, should I spawn a different process for each client ? What if a client requests trace for one domain, and again(before the full result is provided to him) requests for another. Thanks in advice
Client side code :
<script type="text/javascript">
var ws = new WebSocket("ws://example.com:8080/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
Question: What would be a comparable solution to the example at this link, except implemented using gevent-socketio and Socket.io.js with bottle? I'm looking for the minimal solution that will simply pass some traffic in a loop from the client to the server and back to the client using gevent-socketio, Socket.io.js, and bottle.
Background: I have developed a simple web-app that provides a web-based terminal for a remote custom shell (cli) on the server. The browser (client) collects shell commands from a form input field, passes the command over a web-socket to a gevent.pywsgi.WSGIServer handling the requests via the geventwebsocket.WebSocketHandler handler, which supplies the command to the shell, while asynchronously returning output via the socket to a textarea field in a form in the client's browser. This is based on a great, little example provided by the bottle team:
http://bottlepy.org/docs/dev/async.html#finally-websockets
Provided here for redundancy:
example_server.py:
from bottle import request, Bottle, abort
app = Bottle()
#app.route('/websocket')
def handle_websocket():
wsock = request.environ.get('wsgi.websocket')
if not wsock:
abort(400, 'Expected WebSocket request.')
while True:
try:
message = wsock.receive()
wsock.send("Your message was: %r" % message)
except WebSocketError:
break
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError
server = WSGIServer(("0.0.0.0", 8080), app,
handler_class=WebSocketHandler)
server.serve_forever()
client.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://example.com:8080/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
</head>
</html>
Motivation: My existing app works great in the latest version of Firefox and Chrome. IE support is non-existent, and Safari compatibility is middlin'. I'm ultimately looking for a cross-browswer solution to communicate shell commands and output between the client and server. If I had a simple example for bottle, I think I could move forward more quickly.
Incidentally, I looked at the gevent-socketio examples and even a bottle example, but all of these examples are too different from the above simple example for me to make the leap in application. (The gevent-socketio examples look nothing like the bottle apps, which which I'm familiar. And, the bottle example doesn't actually show how to communicate with the client.)
Thanks! :)
Circus! the process runner and watcher built on top of zmq, use bottle and socketio for the web interfaces:
https://github.com/mozilla-services/circus/blob/master/circus/web/circushttpd.py
https://github.com/mozilla-services/circus/blob/master/circus/web/server.py
The source code is simple enough for helping you to get started to build a bigger app with bottle and socketio.
Otherwise, I advice you to move to sockjs! which a more generic implementation with better support for different backends.
This other thread can help you :
SockJS or Socket.IO? Worth to recode ajax-based page?