Emit can easily send data, for example:
Socket. emit ('action'); indicates that an action command is sent, which is a string and can be written as follows when receiving the command from the other end: socket. on ('action', function (){...});
Socket. emit ('action', data); indicates that an action command and data are sent. When receiving data from the other end, you can write it as follows: socket. on ('action', function (data ){...});
Socket. emit (action, arg1, arg2); indicates that an action command is sent and there are two other data. When receiving the data from the other end, you can write it as follows: socket. on ('action', function (arg1, arg2 ){...});
Socket. emit (action, arg1, arg2, arg3, arg4); If there are multiple parameters, what do you mean?
The emit method contains callback functions, such:
Socket. emit ('action', Data, function (arg1, arg2 ){...}); there is a callback function that can be called at the other end, and the other end can be written as follows: socket. on ('action', function (data, FN) {fn ('A', 'B ');});
The data above can contain 0 or more data, and the number of parameters in the function can be changed at the other end. The number and sequence of parameters in the function should be consistent with that in sending.
The above FN indicates the parameter passed by another end. It is a function. If you write FN ('A', 'B'), the callback function is executed. Multiple callbacks cannot be written for a single sending. Otherwise, only the last callback takes effect. The callback should be used as the last parameter.
Example: a js file (containing a helloworld.html file (containing the following client) is stored in the directory of the server, and the server is started to access http: // 127.0.0.1/
Client:
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML>
Server:
VaR Server = require ('HTTP '). createserver (handler); var IO = require ('socket. io '). listen (server); var FS = require ('fs'); server. listen (80); function handler (req, Res) {FS. readfile (_ dirname + '/helloworld.html', function (ERR, data) {If (ERR) {res. writehead( 500); Return res. end ('error loading index.html ');} res. writehead( 200); Res. end (data) ;}) ;}io. sockets. on ('connection', function (socket) {socket. on ('msg ', function (data, FN) {console. log ('Received message from client: '+ data); FN ('the server has been successfully received your message:' + data );});});