简体   繁体   English

Socket.io没有从客户端发送到服务器

[英]Socket.io not emitting from Client to Server

I have a server-client connection protocol established as such: 我有这样建立的服务器-客户端连接协议:

Server: 服务器:

const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io').listen(server);
io.on('connection', function (socket) {
    "use strict";
    socket.emit('connectionSuccess', {});
    socket.emit('initmap', map.objects);

    io.on('test', function (event) {
        console.log('received client emit');
    });
});

Client: 客户:

socket.on('connectionSuccess', function (event) {
    console.log('connection successful');
    socket.emit('test', {"test": "data"});
});

When the server runs on a specified port, and a user accesses the client, a connection is established and the client console outputs a connection success. 当服务器在指定的端口上运行并且用户访问客户端时,将建立连接,并且客户端控制台将输出连接成功。

The server is able to emit 'initmap' to send data to the client for it to be read, however, the same can't be said for sending test data from the client back to the server upon connection. 服务器能够发出“ initmap”以将数据发送到客户端以供读取,但是,在连接时不能说相同的测试数据从客户端发送回服务器。

Why is it that emits seem to only work from server to client and not client to server in this instance? 为什么这种情况下发出的光似乎仅在服务器到客户端之间起作用,而在客户端到服务器之间却不起作用?

You should listen for test events on the socket instance, not on the server instance: 您应该在套接字实例而不是服务器实例上侦听test事件:

io.on('connection', function (socket) {
  ...
  socket.on('test', function (event) {    // <-- `socket.on()` instead of `io.on()`
    console.log('received client emit');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM