WebSockt (socket.io) understanding based on NodeJS

The business basis of this article is based on the direct broadcast chat room (IM) application of socket. IO based on NodeJS. The specific framework of the project is as follows: Express + mongodb + socket. IO Before introducing socket. IO, it is necessary to understand the basic principle of webSocket.Copy the code

First, webSocket’s past life and present life

1. What is webSocket? 2. How to use it? 3. Frequently used scenarios? 4, need to pay attention to the place well, we will follow the above four points to analyze.Copy the code
1. What is websocket

Official document interpretation: webSocket

This is the official MDN document. The detailed content needs the reader to read carefully, the author only introduces the problem that is easy to make mistakes here. WebSockets are an advanced technique for creating bidirectional sessions between servers. With this API you can send messages to the server and receive event-driven responses without polling the server for data. Of course, this is only meant to solve the problem of not polling the server for data. It's not official enough to say that. In B/S software projects, the client obtains server messages through HTTP and HTTPS, but the default HTTP protocol only supports the request response mode, which simplifies the Web server, reduces the server burden, and speeds up the response speed of the website. But can not meet our real-time message push, chat room and other functions, this time websocket this as a Unix process communication mechanism was grafted to the network communication between applications, thus has today's socketCopy the code
2. Websocket: Communication model

WebSocket is a network technology of full duplex communication between browser and server provided by HTML5. Depending on this technology can realize the client and server long connection, two-way real-time communication. Features: Event-driven, asynchronous use of WS or WSS sockets, implementation of true push functionality here ws and WSS difference is the same as HTTP and HTTPS difference (security) disadvantage is compatibility (this year is 2017, I think we can forget about that.)Copy the code
3. Websocket client
A) Connection classes: 1. Send () sends data to a remote server. 2. Close () closes the Websocket connection. Onopen: this event is triggered when a network connection is established. Onerror: this event is triggered when a network error occurs. Onclose: this event is triggered when webSocket is closed The event that is triggered when a message is received from the server. It is also the most important listening event in communication. We can extend our onMessage events by defining the types of various onMessage events. C) WebSocket also defines a readyState property: 3. CLOSING(2) The Websocket is CLOSING the connection with the server. 4. The Websocket has closed its connection to the serverCopy the code
4. Websocket server
The server is like a distribution center, but connections must first be created through CONNECT to form long connections for WS. If the server emit event is emitted, then the server will need to listen for the on method to listen for the same event. If the server emit event is emitted, then the server will need to listen for the same event. There is a single-room and multi-room concept, which we will discuss in detail later in the introduction) where all connected users are notified of this message, and a broadcast is triggered to the client while listening for the message triggered by the server. At this point, all users on the current WS connection line will emit to this event, thus implementing the broadcast. Now, this is a long paragraph, and it might not be easy to understand, but if you write a demo like this you'll understand a lot.Copy the code

Socket. IO is a webSocket framework based on nodeJs

Socket. IO is the main character of this article, because it makes a very perfect encapsulation of webSocket, and puts forward the concept of multi-room multi-namespace, so that the simultaneous existence of multiple chat rooms is no longer a problem, so, the following will be detailed to introduce the socket. IO frameworkCopy the code

Socket. IO This is the official website

We can see a very concise socket. IO application method in the official website. It also shows a universal IM (although f**k XXX is often seen here)Copy the code

IO socket. IO socket. IO

1. Server API 2. Client API 3Copy the code

This is to introduce these three

1, the Server API
The server initializes the IO objectCopy the code
const io = require('socket.io') ();// or
const Server = require('socket.io');
const io = new Server();
Copy the code
I'm using nodeJS so I can just use Express or KOA2 and then create the HTTP-Server serviceCopy the code
const socket = require('socket.io');

var app = express()

var server = http.createServer(app)

io = socket(server)

io.on('connection'.function(socket) {
	// to do somethings
})

Copy the code
This step can easily create a socket server using NodeJS + ExpressCopy the code
2, the Client API
The above steps have done a number of operations on the server side, which need to create a connection on the server side. The first step is to reference the socket file in the front endCopy the code

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io('http://localhost');
</script>
const io = require('socket.io-client');
// or with import syntax
import io from 'socket.io-client';

Copy the code
And then create the connectionCopy the code

const socket = io();

Copy the code
Then trigger the listener 'connection'Copy the code

io.on('connection', (socket) => {
  let token = socket.handshake.query.token;
  // ...
})

Copy the code
If you print debug on the server, you can easily complete the first socket linkCopy the code
3、 Rooms and NameSpace
Finally, the concepts of rooms and namespace play an important role in multi-room chat rooms. Here's the concept of rooms. You can check out the socket. IO website for namespace informationCopy the code

// Broadcast to everyone in the room except yourself

socket.broadcast.to(roomId).emit('msg', {	
	// take somethings
})

// Broadcast to yourself in the current room

socket.emit('msg', {
	// take somethings
})


// Broadcast to everyone in the current room

socket.to(roomId).emit('msg', {	
	// take somethings
})

Copy the code
And then combined with the above monitoring, triggering methods to complete a series of requirements.Copy the code

Well, today first here, any questions, you can leave a message to learn from each other. Welcome recommendation ~~~

Attach github address