我正在開發使用nodejs和socket.io的簡單應用程序。 我創建了兩個通道,並且我希望我的客戶端在點擊按鈕時連接一個通道。問題是我不從服務器獲取當點擊按鈕時,JS從客戶端更改套接字名稱空間
響應這是我的代碼:
// SERVER端
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var nameSpaceWeek = io.of('/week');
var nameSpaceDay = io.of('/day');
app.get('/', function(req, res){
res.sendfile('MDC.html');
});
io.on('connection', function(socket){
console.log("User = " + socket.id)
});
nameSpaceDay.on('connection', function(socket){
console.log('someone connected on namespace day');
nameSpaceDay.emit('hiDay', 'Hello everyone on namespace day!');
});
nameSpaceWeek.on('connection', function(socket){
console.log('someone connected on namespace week');
nameSpaceDay.emit('hiWeek', 'Hello everyone on namespace week!');
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
//客戶端
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setDay(){
console.log("setDay");
socket = io.connect('/day');
console.log(socket)
}
socket.on('hiDay',function(data){
console.log("hiDay")
console.log("data = ." + data + ".")
document.getElementById('message-container').innerHTML = 'Update day'
console.log("data = ." + data + ".")
});
function setWeek(){
console.log("setWeek");
socket = io.connect('/week');
console.log(socket)
}
socket.on('hiWeek',function(data){
console.log("hiWeek")
document.getElementById('message-container').innerHTML = 'Update Week'
//document.getElementById('message-container').innerHTML = data
console.log(data)
});
</script>
<body>
<div id="message-container"></div>
<div id="error-container"></div>
<button type="button" name="button" onclick="setWeek()">Week</button>
<button type="button" name="button" onclick="setDay()">Day</button>
</body>
在我的客戶端中,我創建了兩個按鈕,當我點擊一個按鈕時,我想更改套接字名稱空間
我所做的更改,但它是相同的結果 –
@baudic_j - 當我與所需的更改運行它,它只是對我很好。你顯然沒有正確地做出改變,或者我不清楚你應該做什麼。 – jfriend00
@baudic_j - 出於某種原因,'setDay()'方法工作正常,但'setWeek()'不是。我正在調查。 – jfriend00