Use socket.io to create a socket.io server. But this server depends on an already created http server.
After the http server is running, use the listen method to attach a socket.io server to the http server.
Socket is a socket.io server created based on server.
When the client establishes a connection with the server, the connection event of the socket.io service is triggered.
The socket parameter in the callback function is the socket port object used to establish a connection between the server and the client.
When a message sent by the client is received, the message event of the socket port object is emitted.
The parameter of the callback function 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 connection between the server and the client is disconnected.
This callback function does not take any parameters.
Server-side server.js code:
Create client index.html code:
This code:/socket.io/socket.io.js is provided by the server-side socket.io class library, and there is no need to actually place a socket.io.js file on the client side.
In the script file, first use the io.connect() method to connect to the server-side socket.io server.
This method returns a client socket port object that establishes a connection with the server.
When a message sent by the server is received, the message event of the client socket port object is triggered.
You can also use the send() method of the client's socket object to send data to the server.
When the server disconnects, the disconnect event of the client socket port object is triggered,
This callback function does not use any parameters.
Note:
The client's message mechanism is completely consistent with the server's message processing mechanism. Because socket.io ensures that the client and server share the same API.
Result after running:
When the browser is closed, the connection with the server is disconnected. At this time, the server triggers the disconnect event and the client disconnects.