服务器不接收客户端套接字。输入输出信息

时间:2022-04-20 19:42:33

I started a simple express+socket.io project. On the server I registered to socket's 'connection' event and upon that I send a message to the client. This works well.

我启动了一个简单的express+socket。io项目。在服务器上,我注册了套接字的“连接”事件,然后向客户端发送消息。这工作很好。

When I receive the message on client side from the server, in this event handler i do socket.emit('message', 'some text');

当我从服务器端收到客户端消息时,在这个事件处理程序中,我做了套接字。发出(“信息”、“文本”);

This message doens't arrive to server. I know it should be very simple and thus I think i missing something stupid. Any help appreciated.

此消息不会到达服务器。我知道这应该很简单,所以我觉得我漏掉了一些愚蠢的东西。任何帮助表示赞赏。

server code:

服务器代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

io.on('connection', function (socket) {
    console.log('a user connected');
    io.emit('server-message', 'hello socket.io server');
});

io.on('message', function(message) {
    console.log(message);
});

client code:

客户机代码:

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

socket.on('server-message', function (message) {
            console.log(message);
            socket.emit('message', 'hello socket.io from browser');
         });

1 个解决方案

#1


3  

Looks like io.emit('server-message', 'hello socket.io server'); should be changed to socket.emit('server-message', 'hello socket.io server'); You would then need to move the following into the connection event listener:

看起来像io。发出(服务器消息,你好插座。io服务器”);应该更改为套接字。发出(服务器消息,你好插座。io服务器”);然后,您需要将以下内容移动到连接事件侦听器中:

io.on('message', function(message) {
  console.log(message);
});

and change it to

和改变它

socket.on('message', function(message) {
  console.log(message);
});

#1


3  

Looks like io.emit('server-message', 'hello socket.io server'); should be changed to socket.emit('server-message', 'hello socket.io server'); You would then need to move the following into the connection event listener:

看起来像io。发出(服务器消息,你好插座。io服务器”);应该更改为套接字。发出(服务器消息,你好插座。io服务器”);然后,您需要将以下内容移动到连接事件侦听器中:

io.on('message', function(message) {
  console.log(message);
});

and change it to

和改变它

socket.on('message', function(message) {
  console.log(message);
});