【问题标题】:Send data from Python to node a server with socket (NodeJS,Socket.io)使用套接字(NodeJS,Socket.io)将数据从 Python 发送到节点服务器
【发布时间】:2016-12-15 19:11:20
【问题描述】:

我试图将传感器数据(在 python 中)从我的树莓派 pi3 发送到我的本地节点服务器。

我找到了一个名为requests 的python 模块,用于将数据发送到服务器。

在这里,我尝试使用 socket.io 将值 22(稍后会有传感器数据)从我的树莓派 pi3 发送到我的本地节点服务器。requests.get() 有效,但 put 命令不发送数据。

你能告诉我错误在哪里吗?

#!/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'});

在我的 server.js 中,我尝试获取数据,但不知何故没有收到任何东西

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 + '/');

【问题讨论】:

    标签: python node.js websocket socket.io


    【解决方案1】:

    您正在使用 Python 中的 HTTP PUT,但您正在使用 nodejs 端的 websocket 服务器进行侦听。

    要么有节点监听 HTTP POST(我会使用 POST 而不是 PUT):

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

    或者在 python 端有一个 websocket 客户端:

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

    持久的 websocket 连接可能是最好的选择。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2018-11-23
    • 2020-06-01
    • 1970-01-01
    • 2019-08-27
    • 2012-12-31
    • 1970-01-01
    相关资源
    最近更新 更多