2017-02-12 26 views
0

我正在嘗試遵循this示例,但在瀏覽器中看不到消息「來自客戶端的Hello World」。對於這個問題,我沒有看到Client connected...不返回消息給客戶端的示例

我確實看到了Hello World和窗體。

app.js

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

app.use(express.static(__dirname + '/bower_components')); 

io.on('connection', function(client) { 
    console.log('Client connected...'); 

    client.on('join', function(data) { 
     console.log(data); 
     client.emit('messages', 'Hello from server'); 
    }); 
});  

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

server.listen(4200); 

的index.html

<!doctype html> 
<html lang="en"> 
    <script> 
     var socket = io.connect('http://localhost:4200'); 
     socket.on('connect', function(data) { 
      socket.emit('join', 'Hello World from client'); 
     }); 
     socket.on('messages', function(data) { 
      alert(data); 
     }); 
    </script> 
    <head>  
    </head> 
    <body> 
     <h1>Hello World!</h1> 
     <div id="future"></div> 
     <form id="form" id="chat_form"> 
      <input id="chat_input" type="text"> 
      <input type="submit" value="Send"> 
     </form> 
     <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
     <script src="/socket.io/socket.io.js"></script>    
    </body> 
</html> 

回答

2

<script>標籤簡直位於<head><body>標籤。如果你要操縱DOM和不使用domready中功能檢查DOM是否準備好了沒有,那麼你應該把你的身體標記結束所有腳本標記只是</body>前:

<!doctype html> 
<html lang="en"> 
    <head> 
    <title>My App</title> 
    </head> 
    <body> 
    <h1>Hello World!</h1> 
    <div id="future"></div> 
    <form id="chat_form"> 
     <input id="chat_input" type="text"> 
     <input type="submit" value="Send"> 
    </form> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
     var socket = io.connect('http://localhost:4200'); 
     socket.on('connect', function(data) { 
     socket.emit('join', 'Hello World from client'); 
     }); 
     socket.on('messages', function(data) { 
     alert(data); 
     }); 
    </script> 
    </body> 
</html> 
相關問題