This article mainly introduces node. use socket in js. io method. For more information, see use socket. use io to create a socket. i/O server. however, this server depends on a created http server.
After the http server is running, use the listen method to append a socket. io server to the http server.
The Code is as follows:
Var sio = require ("scoket. io ");
Var socket = sio. listen (server );
Socket is a socket. io server created on the server.
When a connection is established between the client and the server, the connection event of socket. io service is triggered.
The Code is as follows:
Socket. on ("connection", function (socket ){
});
The socket parameter in the callback function is the socket port object used to establish a connection between the server and the client.
When receiving a message sent by the client, the message event of the socket port object is sent.
The Code is as follows:
Socket. on ("message", function (msg ){
});
The callback function parameter is the message sent by the client.
You can use socket. send (msg) to send a message to the client.
The disconnect event is triggered when the client-side connection is disconnected on the server.
The Code is as follows:
Socket. on ("disconnect", funciton (){
});
This callback function does not apply to any parameters.
Server. js code:
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 ){
Console. log ("Client Connection established ");
Socket. send ("hello ");
Socket. on ("message", function (msg ){
Console. log ("received a message:" + msg );
});
Socket. on ("disconnect", function (){
Console. log ("client disconnected .");
});
});
Create the client index.html code:
The Code is as follows: