2016-06-23 43 views
0

我正在與Socket.io一起學習NodeJS 我有一個非常簡單的聊天頁面。但我不知道我的錯誤在哪裏。無法使用NodeJS/Socket.io在HTML文件中檢索簡單的廣播消息

這裏是我的簡單的代碼:

index.js

var express = require('express'); 
var app = express(); 
app.use('/', express.static(__dirname + '/')); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

app.get('/', function(req, res){ 
    //res.send('<h1>Hello World</h1>'); 
    res.sendFile(__dirname + '/index.html'); 
}); 

io.on('connection', function(socket){ 
    //console.log('a user is connected!'); 
    socket.on('disconnect', function() { 
     //console.log('user disconnected!'); 
    }); 
    socket.on('chat message', function(msg) { 
     io.emit('chat message: ' + msg); 
    }); 
}); 

http.listen(3000, function() { 
    console.log('listening on *:3000'); 
}); 

的index.html

<body> 
    <ul id="messages"></ul> 
    <form action=""> 
    <input id="m" autocomplete="on" /><button>Send</button> 
    </form> 
    <script type="text/javascript" src="jquery-1.12.4.js"></script> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
    var socket = io(); 
    $('form').submit(function() { 
     socket.emit('chat message', $('#m').val()); 
     $('#m').val(''); 
     return false; 
    }); 
    socket.on('chat message', function(msg) { 
     console.log(msg); //NO VALUE? 
    }); 
    </script> 
</body> 

我不能讓在這條線的值:

socket.on('chat message', function(msg) { 
      console.log(msg); //NO VALUE? 
     }); 
無法在客戶端上收到
+1

試** VAR插座= 10(」 http:// localhost:3000「); ** < - 你應該在http:// localhost之前,我不知道評論不顯示。 – modernator

+0

仍然有同樣的效果。沒有價值。 – Jerielle

+0

Socket.io和Node.JS使用Websocket協議,這與'socket'非常不同 - 我正在編輯你的問題來修復標記。請注意。 – Myst

回答

2

的消息,因爲隨着

// Server: Receive and send message 
socket.on('chat message', function(msg) { 
    io.emit('chat message: ' + msg); 
} 

你發出一個名爲chat message: ${msg}的事件,但是這是你是不是在客戶端監聽的事件。 發出事件時,首先定義事件名稱,然後將數據指定爲second parameter in JSON format。將上面的代碼更改爲

// Server: Receive and send message 
socket.on('chat message', function(data) { 
    io.emit('chat message', { message : data.message }); 
} 

將以消息作爲數據向客戶端發送事件。將事件從客戶端發送到服務器時,應用相同的語法。因此,改變

// Client: Send message 
$('form').submit(function() { 
    socket.emit('chat message', $('#m').val()); 

// Client: send message 
$('form').submit(function() { 
    socket.emit('chat message', {message : $('#m').val()}); 

當服務器回答您的活動,那麼你就可以接收和按如下方式訪問消息:

// Client: Receive message 
socket.on('chat message', function(data) { 
    console.log(data.message); // VALUE :-) 
}); 
+0

感謝一個非常明確的解釋。無論如何,我正在按照這個教程,我只是添加一些代碼行。 http://socket.io/get-started/chat/ – Jerielle