2016-12-27 42 views
0

我是新手到socket.io世界,我是想一個簡單的程序如下socket.io發出不工作

服務器端

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

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

io.on('connection', function(socket){ 
    console.log('socket listening.'); 
socket.on('chat_message', function(msg){ 
     console.log('message: ' + msg); 
     }); 
}); 

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

客戶端代碼片段

<script src="/socket.io/socket.io.js"></script> 
<script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
<script> 
    var socket = io(); 
    $('form').submit(function(){ 
    socket.emit('chat_message', $('#m').val()); 
    $('#m').val(''); 
    return false; 
    }); 
</script> 
    <body> 
    <ul id="messages"></ul> 
    <form action=""> 
     <input id="m" autocomplete="off" /><input type="submit" id="submit" name="submit">Send</input> 
    </form> 
    </body> 

所以在這裏我看不到要打印的信息。有人能幫我理解相同的原因嗎?

作爲一個嘗試,我也在服務器端做了以下事情。

io.on('chat_message', function(msg){ 
     console.log('message: ' + msg); 
     }); 

仍然沒有工作。

我嘗試引用下面的鏈接,但無法理解相同的原因。

socket.io-client connecting, but not emitting

回答

0

腳本標籤應駐留在<head><body>元件;你的不在裏面。所以首先將它們移動到最後的body標籤內,以確保在運行腳本之前加載DOM。

您的第一個輸入沒有任何類型。添加type="text",以便您可以檢索其值。

您已關閉第二個輸入標籤。 <input>標籤是自動關閉的。無需關閉。 (您可以通過設置值value屬性:value="Send"

<!DOCTYPE html> 
<html> 
    <head> 
    <title>socket.io</title> 
    </head> 
    <body> 
    <ul id="messages"></ul> 
    <form> 
     <input type="text" id="m" autocomplete="off"> 
     <input type="submit" id="submit" name="submit" value="Send"> 
    </form> 
    <script src="/socket.io/socket.io.js"></script> 
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
    <script> 
     var socket = io(); 
     $('form').submit(function(){ 
     socket.emit('chat_message', $('#m').val()); 
     $('#m').val(''); 
     return false; 
     }); 
    </script> 
    </body> 
</html>