2015-11-07 93 views
0

我正在處理涉及實時溫度的項目,並且有一個設備通過get路由通過服務器發送臨時數據併發送到套接字。然後,我希望服務器連接到原始套接字並將數據發送到正在由客戶端讀取的新數據。發射後無法連接到插座

這裏是我的app.js

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

server.listen(8080); 

app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html'); 
}); 


app.route('/:temp') 
    .get(function (req, res){ 
     var temp = req.params.temp; 
     res.end(temp); 
     io.sockets.on('connection', function(socket){ 
      socket.emit('send temp', temp); 
     }); 
    }); 

io.sockets.on('connection', function(socket){ 
    socket.on('send temp', function(data){ 
     console.log('connected to send temp');//this never shows in the console 
     io.sockets.emit('new temp', data); 
    }); 
}); 

在app.js的航線代碼工作正常。當我打localhost:3000/test並更改客戶端連接到'send temp'(而不是'new temp')時,會輸出'test'。

這裏是我的客戶

var socket = io.connect(); 
     var $temp = $('#temp');   


     socket.on('new temp', function(data){ 
      $temp.html("Temp: " + "<br/>"+data); 
     }); 

我運行的節點版本4.1.2,1.3.7插座並表達4.10.8的相關部分。 我想知道爲什麼我無法第二次連接到原始套接字。或者這可能不是我的問題。我學習了許多「聊天」教程,並試圖通過嘗試做我想做的事而沒有獲得任何成功。

最終,我試圖發生的事情是讓客戶端實時查看客戶端命中/:temp,然後讓其他客戶端實時獲取該數據。

這對我來說仍然有點新,所以任何幫助表示讚賞。

回答

0

您的代碼示例在服務器上爲'send temp'消息註冊消息處理程序。客戶端爲'new temp'消息註冊消息處理程序。

然後兩個人(客戶端和服務器)坐在一起,等待某人首先發送一條消息,但根據你公開的代碼,沒有人會這樣做。

我真的不明白你的代碼的意圖是什麼,但我看到了幾個問題。

首先,你不想安裝監聽器的代碼裏面connection事件:

app.route('/:temp') 
    .get(function (req, res){ 
     var temp = req.params.temp; 
     res.end(temp); 
     io.sockets.on('connection', function(socket){ 
      socket.emit('send temp', temp); 
     }); 
    }); 

爲什麼你只開始監聽連接事件當你得到一個特定的路由處理。而且,爲什麼每當該路線被擊中時又添加另一個事件處理程序。這段代碼是完全錯誤的。我不知道你以爲你想用它達到什麼目的,但這不是做事的方式。

其次,此代碼正在等待客戶端發送'send temp'消息,當它收到消息時,會嘗試將消息廣播給所有客戶端。但是,您披露的客戶部分從未發送過'send temp'消息。

io.sockets.on('connection', function(socket){ 
    socket.on('send temp', function(data){ 
     console.log('connected to send temp');//this never shows in the console 
     io.sockets.emit('new temp', data); 
    }); 
}); 

第三關,請描述你試圖用言語來完成,所以我們可以更好地瞭解,爲了做到這一點,建議什麼代碼到底是什麼。


編輯

現在你已經在這裏描述的實際問題:

最終什麼,我想有發生的是有一個客戶端命中/:溫度過高 和結束實時閱讀,然後讓其他客戶端實時獲取數據。

這是一個小更容易提出一個解決方案:

在服務器上:

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

server.listen(8080); 

app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html'); 
}); 


app.get('/:temp', function (req, res) { 
    var temp = req.params.temp; 
    res.end(temp); 
    // send this temperature to all connected clients 
    io.emit('new temp', temp); 
}); 

在客戶端:

var socket = io.connect(); 
var $temp = $('#temp');   
socket.on('new temp', function(data){ 
    $temp.html("Temp: " + "<br/>"+data); 
}); 
+0

感謝您抽出寶貴的時間。我更新了一些清晰的內容並解釋我正在嘗試做什麼。我想我正在接近這個錯誤,但期待您的反饋。 – cTwice

+0

@cTwice - 根據你試圖解決的實際問題的描述,我在答案的最後添加了一個新的部分。 – jfriend00

+0

這就是我正在尋找的,感謝幫助。 – cTwice