从dgram socket udp4调用socket.io

时间:2014-01-21 02:40:45

标签: json udp socket.io arduino

我正在开发的一些小应用程序中遇到一些问题。

我有一个带温度传感器的Arduino,我想将值发送到nodejs服务,然后将其显示给网页。我想使用socket.io,但我只能使用从arduino到服务器(以太网)的UDP连接。只是为了保持传感器值刷新,似乎我必须从UDP服务调用一个io套接字,但我不能。

我的socket.io在我从网页上调用它时有效。

var io = require('socket.io').listen(3000);
 io.sockets.on('connection', function (socket) {
socket.on('message', function (message) {
    console.log("Got message: " + message);
    io.sockets.emit('SensorList', { 'temperature': temp });
      });
 });

这是读取arduino数据包的UDP服务:

 var dgram = require("dgram");
 var server = dgram.createSocket("udp4");
 var fs = require('fs');
 **var io = require('socket.io');**

 var crlf = new Buffer(2);
 crlf[0] = 0xD; //CR - Carriage return character
 crlf[1] = 0xA; //LF - Line feed character
 server.on("message", function (msg, rinfo) { //every time new data arrives do this:
   console.log("server got: " + msg.readUInt16LE(0) + " from " + rinfo.address + ":" + rinfo.port); // you can comment this line out

   **var socket = io.connect('http://localhost:3000');
   socket.on('connect', function () {
    socket.send(msg.readUInt16LE(0));
   });**

 });

 server.on("listening", function () {
    var address = server.address();
    console.log("server listening " + address.address + ":" + address.port);
 });

 server.bind(6000); //listen to udp traffic on port 6000

错误是:      var socket = io.connect('http://localhostit.is:3000'); ^      TypeError:Object#没有方法'connect'          在Socket。 (/Users/xfr/Documents/nodejs/temp1/app2.js:15:19)          在Socket.EventEmitter.emit(events.js:98:17)          在UDP.onMessage(dgram.js:437:8)

如果我擦除所有io部分,我可以在控制台中看到这些值。 如果有另一种方法将两种服务混合在一起..告诉我一些线索,我会进行搜索。 感谢。

1 个答案:

答案 0 :(得分:0)

做到了!

2合1 ......

var http = require('http'),
    dgram = require('dgram'),
    socketio = require('socket.io');
var fs = require('fs');
var app = http.createServer(),
    io = socketio.listen(app),
    socket = dgram.createSocket('udp4');

var crlf = new Buffer(2);
crlf[0] = 0xD; //CR - Carriage return character
crlf[1] = 0xA; //LF - Line feed character

socket.on('message', function(content, rinfo) {
   console.log('got message', content.readUInt16LE(0), 'from', rinfo.address, rinfo.port);
    io.sockets.emit('udp message', content.readUInt16LE(0)); 

});

socket.bind(6000);
app.listen(8000);

在网页方面:

 src="socket.io.min.js" 
 src="jquery.min.js" 
<script> 
var socket = io.connect('http://local_host.com:8000'); 

socket.on('udp message', function(msg) { 
    console.log(msg) ;
    temperature = msg/100;
    $('#temperature h1').html(temperature+'&deg;C');

}); 

</script>

绑定/听取新手问题。