简体   繁体   English

socket.io中的socket变量是什么

[英]What is socket variable in socket.io

I'm new to Node.js and socket.io.我是 Node.js 和 socket.io 的新手。

I go official site of socket.io, and try a tutorial.我去 socket.io 的官方网站,并尝试教程。 http://socket.io/get-started/chat/ http://socket.io/get-started/chat/

It work correctly on my computer.它在我的电脑上正常工作。 But I can't understand essence of its code at all.但我根本无法理解其代码的本质。

QUESTION:what is "socket variable" in below code.问题:下面代码中的“套接字变量”是什么。 And Where is it from?它来自哪里?

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

Maybe "msg variable" is String type variable.也许“msg 变量”是字符串类型变量。 And it is from client side, right?它来自客户端,对吧?

The socket variable is basically a socket to a client. socket变量基本上是客户端的套接字。 The io.on('conection') will be called each time a new client connects and give a socket to subscribe to. io.on('conection')将在每次有新客户端连接并提供订阅的套接字时被调用。

socket.on('chat message' will subscribe on events sent by client associated with that socket instance. socket.on('chat message'将订阅与该套接字实例关联的客户端发送的事件。

Here is the different parts of your program explained:以下是对您程序的不同部分的解释:

io.on('connection', function(socket){ // Waiting for new clients to connect, then return a socket instance
// msg can be any javascript object like a string or array ect.
  socket.on('chat message', function(msg){ // Subscribe on event 'chat message' will be called when client do io.emit
    io.emit('chat message', msg); // Server send to clients
  });
});

Type of the variable msg is not exactly String but more like whatever emitted in the 'chat message' event.变量 msg 的类型不完全是 String,而是更像是“聊天消息”事件中发出的任何内容。 You don't have to emit only strings, you can emit objects too.您不必只发出字符串,也可以发出对象。 In the context of the example, yes.在示例的上下文中,是的。 It is from the client side.它来自客户端。

The variable socket though, socket is the connection between client and the server.变量socket虽然,socket是客户端和服务器之间的连接。 If the server receives a 'chat message' event from that connection, or rather 'socket', it emits a 'chat message' event on all the sockets that it has.如果服务器从该连接接收到“聊天消息”事件,或者更确切地说是“套接字”,它会在它拥有的所有套接字上发出“聊天消息”事件。 The content of the 'chat message' event that server emits to all sockets that are connected to it is the same as the content of the 'chat message' event that client, which sent the chat message, emitted to the server in the first place.服务器向所有连接到它的套接字发出的“聊天消息”事件的内容与发送聊天消息的客户端首先向服务器发出的“聊天消息”事件的内容相同.

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

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