节点服务器无法从Socket.IO接收消息

时间:2015-01-10 18:26:23

标签: node.js sockets

我无法发送"嗨"从客户端到服务器的消息。有套接字连接,我在客户端建立连接时收到一条消息。但是当我尝试将消息发送回服务器时,它无法正常工作。

我尝试过Android和HTML。所以我很确定它的服务器。

NODE

var socket = require('socket.io');
var io;
module.exports = {
    initialize: function(server) {
        io = socket.listen(server);
        io.on('connection', function(socket) {
            socket.emit('message');
            console.log('connected to socket');
        });
        io.on('hi', function(message) {
            console.log(message);
        });
    }
}

HTML

doctype html
html
    head
        title Example
        script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
        script(src='/socket.io/socket.io.js')
        script(type"text/javascript").
            var socket = io.connect('http://localhost:3000')

            socket.on('message', function(data){
                console.log('receive message from server on webpage');
            });
    body
        div.container
            header
                h1 Socket Test
                button#hiButton Send Hi 
    footer
        script(type"text/javascript").
            $('#hiButton').click(function(){
                socket.emit('hi', 'send hi to server from webpage');
            });

1 个答案:

答案 0 :(得分:1)

找到答案

var socket = require('socket.io');
var io;
module.exports = {
    initialize: function(server) {
        io = socket.listen(server);
        io.sockets.on('connection', function(socket) {
            socket.emit('message');
            socket.on('hi', function(message) {
                console.log(message);
            });
            console.log('connected to socket');
        });
    }
}