简体   繁体   English

socket.on inside socket.on 服务器端 api socket.io 在 nodejs

[英]socket.on inside socket.on server side api socket.io in nodejs

Why do we require to put socket.on inside socket.on here?这里为什么要将socket.on放在socket.on里面呢? What does this represent?这代表什么? Is there any other way of writing this?还有其他写法吗?

This is the code of server.js in nodejs.这是nodejs中server.js的代码。

var objExpress = require('express')()
var objHttp = require('http').createServer(objExpress)
var objSocketIO = require('socket.io')(objHttp)

objExpress.get('/', (request, result) => result.send('hello'))

objSocketIO.on('connection', (argSocket) => {
  console.log('A user connected!');
  argSocket.on('message', (argMsg) => {
    console.log(argMsg);
    argSocket.broadcast.emit('message-broadcast-xyz', argMsg)
  })
})

objHttp.listen(3000, () => {
  console.log("Listening on port 3000")
})

Inside of this:在这里面:

objSocketIO.on('connection', argSocket => {
    // here's where you know the socket for a newly connected socket
});

is the only place where you get notified of a newly connected socket.是您收到新连接套接字通知的唯一地方。 If you want to listen for events on that newly connected socket, then this is the place to install those event listeners.如果您想监听新连接的套接字上的事件,那么这里就是安装这些事件监听器的地方。

objSocketIO.on('connection', argSocket => {
    // here's where you know the socket for a newly connected socket
    // and where you can install event listeners on that newly connected socket
    argSocket.on('message', (argMsg) => {
        // here's where you get a message on that connected socket
        // from the previously installed event handler
        argSocket.broadcast.emit('message-broadcast-xyz', argMsg)
    });
});

Why do we require to put socket.on inside socket.on here?这里为什么要将socket.on放在socket.on里面呢?

Well, that's how event driven programming works.好吧,这就是事件驱动编程的工作原理。 You listen for an event by installing an eventListener.您可以通过安装 eventListener 来监听事件。 In this case, when you get an event from your server that a new socket has connected, then you install event listeners on that new socket so you can get events from it.在这种情况下,当您从服务器获得一个新套接字已连接的事件时,您就可以在该新套接字上安装事件侦听器,以便从中获取事件。

Is there any other way of writing this?还有其他写法吗?

Other ways could be dreamed up, but they'd have to be doing something like this under the covers because listening for events is the way you program with servers and sockets in node.js.可以想出其他方法,但他们必须在幕后做这样的事情,因为监听事件是您使用服务器和 node.js 中的 sockets 进行编程的方式。

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

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