不向客户端返回消息的示例

时间:2017-02-12 22:15:06

标签: node.js express socket.io

我正在尝试关注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>

1 个答案:

答案 0 :(得分:2)

<script>标记只能驻留在<head><body>标记中。如果您要操作dom并且不使用 DomReady 函数来检查dom是否准备就绪,那么您应该将所有脚本标记放在body标记的末尾{{{ 1}}:

</body>