First, web-based real-time communication, we all know that there is websocket, in order to develop quickly, this project we adopt Socket.io (client use socket.io-client)
Socket.io is a websocket library that includes the client's JS and server-side Nodejs, and its goal is to build real-time applications that can be used on different browsers and mobile devices. It automatically chooses the best way to implement network real-time application according to the browser from WebSocket, Ajax long polling, IFrame stream and so on.
Very convenient and user-friendly, and supported by a minimum of up to IE5.5Socket.io features: Real-time analytics: Push data to clients that are represented as real-time counters, charts or log customers. Real-time communication and chat: Just a few lines of code can be written as a Socket.io "Hello,world" chat app. Binary stream transfer: Starting with version 1.0, Socket.io supports any form of binary file transfer, such as: Pictures, video, audio, etc. Document merging: Allows multiple users to edit a document at the same time, and to see changes made by each user.
Socket.io Common events: //Send to current clientSocket.emit (' Hello ', ' Can you hear me? ', 1, 2, ' abc '); //sent to all clients except the senderSocket.broadcast.emit (' broadcast ', ' Hello friends! '); //Sent to all clients in the ' game ' room except the senderSocket.to (' game '). Emit (' nice game ', "Let's play a game"); //Sent to all clients in the ' game1 ' or ' game2 ' room except the senderSocket.to (' game1 '). to (' game2 '). Emit (' nice game ', "Let's play a game (too)"); //Sent to all clients in the ' game ' room, including the senderIo.inch(' Game '). Emit (' big-announcement ', ' the game would start soon ');
Second, Socket.io and express link
Const APP = Express ()// Here you need to use Express to wrap the Socket.io const Server = require ('http ' = Require (' Socket.io ') (server) Server.listen (function() { console.log (' Node app start At Port 9094 ')})
Third, the use of Socket.io
1. Client code1). Introducing Client socket.io-Client Import io from' Socket.io-client ' 2). Linked Server Const socket= Io (' ws://localhost:9094 ') //WS is the transport protocol for WebSocket3). Send a message on the client to the server Socket.emit (' Sendmsg ', msg)//Sendmsg is a client-broadcast event that can be heard on the server2. Server-side code Io.on (' Connection ',function(socket) {//the server uses Socket.on to listen to events sent by the clientSocket.on (' sendmsg ',function(data) {//When the supervisor hears this, the server can tell the client that he has receivedIo.emit (' recvemsg ', Chatmsg)}) })3. Client Socket.on (' Recvemsg ',function(data) {//Client monitoring recvemsg on the server side //........})
The above is the use of Socket.io with Express, below we look at similar real-time chat social software chat model is how to design
A full stack project on vue+mysql+express (v)------Live chat Section Socket.io