Node.js socket.io服务器回调无法正常工作

时间:2022-03-29 19:00:30

I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.

我正在研究一个简单的Node.js双向客户端\服务器通信通道,我试图在服务器上使用socket.io,在客户端上使用socket.io-client。

I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.

我已经插入了下面的代码,因为你会发现它是非常基本的东西,而且我在我的本地机器上运行 - 以最小化复杂性。

The behaviour I'm seeing is:

我看到的行为是:

  1. I start the server.
  2. 我启动服务器。

  3. The server logs 'Server started' to the console.
  4. 服务器将“Server started”记录到控制台。

  5. I start the client.
  6. 我启动了客户端。

  7. The client logs 'Server is ready!'
  8. 客户端日志'服务器已准备就绪!'

  9. Nothing else happens...
  10. 没有其他事情发生......

What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').

我期望的是服务器记录'客户端就绪!'消息,然后是内容('Ready received')。

I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.

我甚至使用WireShark来嗅探线路,看起来客户端正在按照设计发出消息 - 但是服务器上的回调没有触发。

I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).

我正在运行node v0.8.4 with express v3.1.0,socket.io v0.9.13和socket.io-client v0.9.11(全部通过npm安装)。

Here's the server code...

这是服务器代码......

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

app.configure(function(){
  app.use(express.static(__dirname + '/public'));
});

server.listen(8080);
console.log("Server started");

var io = require('socket.io').listen(server);

io.sockets
     .on('connection', function(socket){ 
          socket.emit('server ready', { msg: 'ready' }) ;
      })

     .on('comms', function(content) {
          console.log('Client is ready!');
          console.log(content);
     });

And here's the client code...

这是客户端代码......

    var clientio = require('socket.io-client');
    var socket = new clientio.connect('http://localhost', { port: 8080 });

    socket
     .on('server ready', function(data){
          console.log('Server is ready!');
          socket.emit('comms', 'Ready received');
    })  

     .on('connect-error', function(error) {
          console.log('Connection Error\n' + error);
    })

     .on('error', function(error) {
          console.log('Socket Error\n' + error);
    })

The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.

socket.io和socket.io-client的文档和示例有点混淆(要慈善),它们似乎是一个移动目标...但从我所知,我认为这应该有效。

I'm hoping someone can give me advice as to where I'm going wrong?

我希望有人可以就我出错的地方给我建议吗?

2 个解决方案

#1


4  

In your server you have this code:

在您的服务器中,您有以下代码:

io.sockets
 .on('connection', function(socket){ 
      socket.emit('server ready', { msg: 'ready' }) ;
  })

 .on('comms', function(content) {
      console.log('Client is ready!');
      console.log(content);
 });

What you should do is something like this:

你应该做的是这样的事情:

io.sockets.on('connection', function(socket){
    socket.emit('server ready', { msg: 'ready' });

    socket.on('comm', function(content){
        console.log('Client is ready!');
        console.log(content);
    });

});

#2


3  

hopefully this is doing more or less what you need it to do. Just a couple of minor changes.

希望这或多或少地做你需要它做的事情。只是一些小的改变。

app.js

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

    // using 'connect' to handle static pages
    app.use(require('connect').static(__dirname + '/public'))
    server.listen(8080);

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

    io.sockets.on('connection', function (socket) {
        socket.emit('server ready', { msg: 'ready' });

        socket.on('comms', function(content) {
            console.log(('Client is ready\n'));
            console.log(content);
        });
    });

index.html

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">

</script>

<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>

<script src="/socket.io/socket.io.js"></script>
</head>

<body>
<script>
(function (d, b) {

    function bindEvents() {
        function doSomething(msg) {
            $.each(msg, function (key, value) {
                console.log('doSomething...');
                $("body").append("<p>" + value + "</p>")
            });
        };

    // var socket = io.connect();
    var socket = io.connect('http://localhost');

    socket.on('server ready', function (msg) {
        console.log('Server is ready!\n', msg);
        doSomething(msg);
        socket.emit('comms', {
            msg: 'Client is Ready'
        });
    });

    socket.on('connect-error', function (err) {
        console.log('Connection Error\n', err);
    });

    socket.on('error', function (err) {
        console.log('Connection Error\n', err);
    });
};

$(document).ready(function () {
    bindEvents()
});

})(jQuery, this)
</script>

#1


4  

In your server you have this code:

在您的服务器中,您有以下代码:

io.sockets
 .on('connection', function(socket){ 
      socket.emit('server ready', { msg: 'ready' }) ;
  })

 .on('comms', function(content) {
      console.log('Client is ready!');
      console.log(content);
 });

What you should do is something like this:

你应该做的是这样的事情:

io.sockets.on('connection', function(socket){
    socket.emit('server ready', { msg: 'ready' });

    socket.on('comm', function(content){
        console.log('Client is ready!');
        console.log(content);
    });

});

#2


3  

hopefully this is doing more or less what you need it to do. Just a couple of minor changes.

希望这或多或少地做你需要它做的事情。只是一些小的改变。

app.js

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

    // using 'connect' to handle static pages
    app.use(require('connect').static(__dirname + '/public'))
    server.listen(8080);

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

    io.sockets.on('connection', function (socket) {
        socket.emit('server ready', { msg: 'ready' });

        socket.on('comms', function(content) {
            console.log(('Client is ready\n'));
            console.log(content);
        });
    });

index.html

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">

</script>

<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>

<script src="/socket.io/socket.io.js"></script>
</head>

<body>
<script>
(function (d, b) {

    function bindEvents() {
        function doSomething(msg) {
            $.each(msg, function (key, value) {
                console.log('doSomething...');
                $("body").append("<p>" + value + "</p>")
            });
        };

    // var socket = io.connect();
    var socket = io.connect('http://localhost');

    socket.on('server ready', function (msg) {
        console.log('Server is ready!\n', msg);
        doSomething(msg);
        socket.emit('comms', {
            msg: 'Client is Ready'
        });
    });

    socket.on('connect-error', function (err) {
        console.log('Connection Error\n', err);
    });

    socket.on('error', function (err) {
        console.log('Connection Error\n', err);
    });
};

$(document).ready(function () {
    bindEvents()
});

})(jQuery, this)
</script>