Nodejs + Socket. io implement communication instance code, nodejssocket. io
Directory structure
D:. │ package.json │ server.js │ └─public index.html socket.io.js
Required Conditions
- Socket. io. js is used to initialize io on the front-end interface.
- Socket. io is used by NodeJs to provide the socket method.
Socket. io. js exists in socket. io-client
Socket. io exists in socket. io
Demonstration Functions
- The client sends a message to the server.
- Notify the client of backend Triggering Events
- Server event triggered when the client leaves
Server
Server. js
Var express = require ('express '); var app = express (); var server = require ('http '). createServer (app); var io = require ('socket. io ') (server); app. use ('/', express. static (_ dirname + '/public'); server. listen (80); // socket I/O. on ('connection', function (socket) {// receives and processes the client's hi event socket. on ('hi', function (data) {console. log (data); // triggers the client event c_hi socket. emit ('C _ Hi', 'Hello too! ')}) // Disconnect the event socket. on ('disconnect', function (data) {console. log ('disconnections ', data) socket. emit ('C _ leave ', 'leaves'); // socket. broadcast is used to broadcast to the entire network (except itself) // socket. broadcast. emit ('C _ leave ', 'someone leaves ')})});
- Connection is used to process socket link events.
- Disconnect handles connection disconnection events
- The backend accepts frontend events
socket.on(EventName,function(date){})
- The backend triggers the frontend event
socket.emit(EventName,msg)
This backend demonstrates that the frontend sends a message to the backend to trigger the hi event. The hi event notifies the frontend through callback when the c_hi event defined by the triggering client is triggered.
Client
Index.html
<! DOCTYPE html>
- The send message button is used to send messages to the server and trigger the hi events defined by the server.
- The exit button is used to exit the page, that is, the socket is automatically disconnected. Trigger the disconnect defined by the server.
Source code download: Socket_jb51.rar
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.