简体   繁体   English

Socket.io客户端套接字未发出

[英]Socket.io Client-Side socket not emitting

So I'm running a simple back-end node app with socket.io communicating with client side javascript running socket.io. 因此,我正在运行一个简单的后端节点应用程序,其中的socket.io与运行Socket.io的客户端JavaScript通信。

I can receive messages just fine on the client (I console log them), but the callback function where I emit an event back to the server is not being received. 我可以在客户端上接收消息(我控制台记录它们),但是没有收到我向服务器发送事件的回调函数。 I think from what I've researched, there just might be some silently failing thing that I cannot see. 我认为,根据我的研究,可能会出现一些我看不到的无声失败的事情。

Client side code: 客户端代码:

socket.on('connection', function(socket) {
    socket.on('welcome', function(data) {
        socket.emit('new_state', { data: '1' });
        console.log(data);
    });

    socket.emit('new_state', {data: '1'});

    socket.on('time', function(data) {
        console.log(data);
        socket.emit('new_state', {});
    });

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

Server Side: 服务器端:

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.sockets.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 3000);

// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
    socket.emit('welcome', { message: 'Welcome!' });
    console.log('connection received');

    io.sockets.on('i am client', function(data) {
        console.log(data);
    });

    io.sockets.on('new_state', function(data) {
        console.log('client->server emits');
        io.sockets.emit('updated_state', { state: [1,2,3,4] });
    });

});



app.listen(3000);

What's working right now is that the app.js logs the connection is received, but it never logs or recognizes any event received from the client. 现在正在工作的是app.js记录接收到的连接,但是它从不记录或识别从客户端接收到的任何事件。 Any thoughts? 有什么想法吗? I really think there's some silent error I am not getting. 我真的觉得我没有得到一些无声的错误。

Use your callback socket inside of the connection. 在连接中使用回调套接字。 The namespace 'i am client' is never emitted from the front-end client, so it does nothing. 命名空间“我是客户端”永远不会从前端客户端发出,因此它什么都不做。 On 'new-state' the server should be. 在'新状态'服务器应该是。

socket.on('new_state', function(data) {
    console.log('From Client ' + data);
    socket.emit('updated_state', { state: [1,2,3,4] });
});

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

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