简体   繁体   中英

Send data from Python to node a server with socket (NodeJS,Socket.io)

I trying to send sensor data (in python) from my raspberry pi3 to my local node server.

I found a module for python called requests to send data to a server.

Here I'm trying send the value 22 (later there will be sensor data) from my raspberry pi3 to my local node server with socket.io.The requests.get() works but the put commmand doesn't send the data.

Can you tell me where the mistake is ?

#!/usr/bin/env python
#

import requests

r = requests.get('http://XXX.XXX.XXX.XXX:8080');

print(r)

r = requests.put('http://XXX.XXX.XXX.XXX:8080', data = {'rasp_param':'22'});

In my server.js I try to get the data but somehow nothing getting received

server.js

var express = require('express')
,   app = express()
,   server = require('http').createServer(app)
,   io = require('socket.io').listen(server)
,   conf = require('./config.json');

// Webserver
server.listen(conf.port);

app.configure(function(){

    app.use(express.static(__dirname + '/public'));
});


app.get('/', function (req, res) {

    res.sendfile(__dirname + '/public/index.html');
});

// Websocket
io.sockets.on('connection', function (socket) {

    //Here I want get the data
    io.sockets.on('rasp_param', function (data){
        console.log(data);
    });

    });
});

// Server Details
console.log('Ther server runs on http://127.0.0.1:' + conf.port + '/');

you are using HTTP PUT from Python, but you are listening with a websocket server on nodejs side.

Either have node listening for HTTP POST (I'd use POST rather than PUT):

app.post('/data', function (req, res) {    
    //do stuff with the data here
});

Or have a websocket client on python's side :

ws = yield from websockets.connect("ws://10.1.10.10")
ws.send(json.dumps({'param':'value'}))

A persistant websocket connection is probably the best choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM