Socket.io服务器没有收到消息

时间:2016-04-01 23:01:56

标签: node.js sockets express 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) {
    //socket.emit('greeting', 'welcome to the chat');
    socket.on('chat', function (msg) {
        console.log('message: ' + msg);
    });
});

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

和客户:

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font: 13px Helvetica, Arial;
        }

        form {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

            form input {
                border: 0;
                padding: 10px;
                width: 90%;
                margin-right: .5%;
            }

            form button {
                width: 9%;
                background: rgb(130, 224, 255);
                border: none;
                padding: 10px;
            }

        #messages {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

            #messages li {
                padding: 5px 10px;
            }

                #messages li:nth-child(odd) {
                    background: #eee;
                }
    </style>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
        //localStorage.debug = '*';
        var socket = io("http://localhost:3000/");
        socket.on('greeting',
            function (msg)
            {
                console.log(msg);
            }
            );
        /*
        $('form').submit(function ()
        {
            socket.emit('chat message', $('#m').val());
            //$('#m').val('');
            return false;
        });
        */
        $("#sendBtn").click(function ()
        {
            socket.emit('chat', $('#m').val());
            return false; 
        });
    </script>
</head>
<body>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off" /><button id="sendBtn">Send</button>
    </form>
</body>
</html>

客户端可以从服务器接收消息,但反过来却无法正常工作。我试过开启调试,但我无法判断我所看到的是对还是错。但是,当我按下网页上的发送时,肯定会发生互动。

以下是客户端的外观:

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要更正绑定元素,您正在尝试绑定到尚未呈现的元素。您需要等待DOM准备好。试试这个。

$(function() {
    $("#sendBtn").on('click', function ()
    {
        socket.emit('chat', $('#m').val());
        return false;
    });
});

像这样包装你的功能,你只是在加载页面时才会执行

相关问题