node.js - 无法使用node.js和socket.io从客户端向服务器发送消息

标签 node.js socket.io

我尝试在几天内使用node.js和socket.io在网络上构建应用程序。我不明白为什么我无法使用socket.io 和服务器node.js 从客户端向服务器发送消息。我可以从服务器到客户端接收消息和事件。但无法从服务器接收客户端的事件。我认为我的库有问题。

我安装的模块node.js

  • express
  • io
  • Jade
  • 网络
  • socket.io
  • socket.io-client

为什么会有socket.io-client和socket.io? 我什至尝试这个例子:code.google.com/p/nodejs-win/wiki/SimpleChatSystem 但还是不行。服务器无法接收来自客户端的任何消息和事件。

代码server.js

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), 
io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 
    console.log("server is start on port 8080");

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

    // Success!  Now listen to messages to be received
    client.on('message',function(event){
        console.log('Received message from client! ',event);
    });
    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});

代码客户端index.html

<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
    <script>

        // Create SocketIO instance
        var socket = new io.connect('localhost',{
            port: 8080
        });
        //socket.connect(); 

        // Add a connect listener
        socket.on('connect',function() {
            log('<span style="color:green;">Client has connected to the server!</span>');
        });

        // Add connecting listener
        socket.on('connecting',function() {
            log('<span style="color:green;">Client is connecting to the server!</span>');
        });
        // Add a connect listener
        socket.on('message',function(data) {
            log('Received a message from the server:  ' + data);
        });
        // Add a disconnect listener
        socket.on('disconnect',function() {
            log('<span style="color:red;">The client has disconnected!</span>');
        });

        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.emit("message",message);
                    socket.send(message);            
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }

        setInterval(function(){ sendMessageToServer(new Date())},5000);

    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>
</body>
</html>

我的客户端日志:https://dl.dropbox.com/u/56440676/client.png

我的服务器日志:https://dl.dropbox.com/u/56440676/server.png

最佳答案

此处错误:

// Sends a message to the server via sockets
function sendMessageToServer(message) {
    socket.emit(message);
    log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}

emit 方法需要两个参数。 第一个 - 事件代码。 第二个 - 事件数据。

正确的解决方案:

// Sends a message to the server via sockets
function sendMessageToServer(message) {
    socket.emit('message', message);
    log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}

关于node.js - 无法使用node.js和socket.io从客户端向服务器发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111311/

相关文章:

javascript - TypeError : By. cssSelector 不是函数

flask - 将 SocketIO 与 Flask 和 uWSGI 一起使用时请求 block 大小无效

node.js - Socket.io - 无法加载文件或 io 未定义

jquery - socket.on 调用其回调的次数过多

node.js - 如何使用 vuex 和 socketio 进行实时增删改查?

node.js - 服务器未收到客户端的鼠标移动数据

mysql - 实现一个mysql数据库来套接字聊天

javascript - grunt.js 的全局安装失败

Node.js 中的 JavaScript 原型(prototype)对象效率

javascript - 我是否需要使用来自 node.js 的 mongodb 进行同步调用/事务?