Socket.io Learning

Introduction

In a hurry, will write more later

Core Concepts

Both the server and client have emit and on functions, which can be considered the core of socket.io. Through emit and on, bidirectional communication between server and client can be easily implemented.

emit: Used to emit or trigger an event. The first parameter is the event name, the second parameter is the data to be sent, and the third parameter is a callback function (generally omitted, but needed when immediate confirmation is required after the other party receives the information). on: Used to listen for an event emitted by emit. The first parameter is the name of the event to listen for, and the second parameter is an anonymous function used to receive data from the other party. The first parameter of this anonymous function is the received data, and if there is a second parameter, it is the function to be returned. socket.io provides three default events (both client and server have them): connect, message, and disconnect. The connect event is automatically triggered when a connection is established with the other party, the message event is triggered when data is received from the other party (usually triggered by socket.send()), and the disconnect event is triggered when the other party closes the connection.

On the server side, distinguish between these three situations:

socket.emit(): Broadcasts to the client that established the connection socket.broadcast.emit(): Broadcasts to all clients except the one that established the connection io.sockets.emit(): Broadcasts to all clients, equivalent to the sum of the above two

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy