我正在處理涉及實時溫度的項目,並且有一個設備通過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,然後讓其他客戶端實時獲取該數據。
這對我來說仍然有點新,所以任何幫助表示讚賞。
感謝您抽出寶貴的時間。我更新了一些清晰的內容並解釋我正在嘗試做什麼。我想我正在接近這個錯誤,但期待您的反饋。 – cTwice
@cTwice - 根據你試圖解決的實際問題的描述,我在答案的最後添加了一個新的部分。 – jfriend00
這就是我正在尋找的,感謝幫助。 – cTwice