Home > Article > Web Front-end > Detailed explanation of socket.io event usage in node_node.js
The socket.io class library can not only send messages to each other, but also send events to each other through the emit method of the socket port object.
emit said it in previous events and now it is said in one sentence: emit is used to manually trigger events.
When using the emit method to send an event, you can use the on method and once method of the socket port object at the other end to listen.
The parameter data in the above callback function: the data carried in the event sent by the other party,
fn: The callback function specified by the other party when sending the event.
Case 1: When the server and client are connected, a news event is sent to the client. The event carries an object whose hello attribute value is "Hello". After receiving the client, it sends my other event event When, "The server has received the data" is output in the console. The client sends the data carried in the event.
Server-side code, server.js
Client index.html code:
One thing can be discovered: execution is always on the listening side, not the manual execution side.
When the client and server are connected, a setName event is sent to the client. The event carries "Zhang San". When the event is triggered, a callback function is specified, and the callback function outputs 2 parameter values to the console.
回调函数实在触发端执行的.