This article mainly introduces socket in node. io event Usage Details. For more information, see socket. the 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.
In the previous event, emit said that it was used to manually trigger the event.
The Code is as follows:
Socket. emit (event, data, function (data1, data2 ......){
});
When you use the emit method to send events, you can use the on method of the socket port object on the other end to listen once.
The Code is as follows:
Socket. on (event, function (data, fn ){
});
Socket. once (event, function (data, fn ){
})
The parameter data in the preceding callback function: the data carried by the event sent by the other party,
Fn: the callback function specified by the other party when sending the event.
Case 1: After the server and the client are connected, a news event is sent to the client. The event carries an object whose hello attribute value is "hello ". when receiving the my other event from the client, output "server receives data" + data contained in the event sent by the client in the console.
Server code, server. js
The Code is as follows:
Var http = require ("http ");
Var sio = require ("socket. io ");
Var fs = require ("fs ");
Var server = http. createServer (function (req, res ){
Res. writehead( 200, {"Content-type": "text/html "});
Res. end (fs. readFileSync ("./index.html "));
});
Server. listen (1337 );
Var socket = sio. listen (server );
Socket. on ("connection", function (socket ){
Socket. emit ("news", {hello: "hello "});
Socket. on ("my other event", function (data ){
Console. log ("server received information % j", data );
});
});
Client index.html code:
The Code is as follows: