WebSocket technical explanation

  socket.io, websocket

WebSocket

WebSocketYesHTML5A network technology for full duplex communication between browser and server is initially provided.

At present, many websites use the technology to realize instant messaging.Polling.PollingIt is sent by the browser to the server at a specific time interval (for example, every 1 second)httpqueryinfo, and then by the server to return the latest data to the customer service browser, this way has a big drawback, isTake up a lot of bandwidth.

The latest polling results areComet-AJAX. But although this technology can reachfull duplexHowever, the request still needs to be made.

UseWebSocket, browsers and servers only need toDo a handshake, and then between the browser and the serverA fast passage is formed., between the twoData can be directly transmitted to each other.. Moreover, it brings us two major benefits in realizing instant service:

Save resourcesCommunicating with each otherHeaderIt’s very small.-ProbablyOnly 2 Bytes.
Push information: No client request is required, the server canActively transmit data to clients.

socket.io

Socket.IOIs aWebSocket library, includingJs at client and nodejs at server, its goal is toBuild real-time applications that can be used on different browsers and mobile devices.

Characteristics of socket.io

  • Ease of usesocket.ioEncapsulates the server and client, which is very simple and convenient to use.

  • cross platformsocket.ioSupport cross-platform, which means you have more choices and can develop real-time applications on your favorite platform.

  • Adaptive: It will automatically retrieve data from theWebSocketAJAX long pollingIframe streamAnd so on all kinds of ways to choose the best way to realize the network real-time application, very convenient and humanized, and support the browser as low as IE5.5.

Installation deployment

npm install socket.io

Service monitoring

socket.ioThe start-up of the server is very simpleSocket.io module.

var io = require('socket.io');

Then callListen function, passed inPort number to listen on, start service listening. Port 80 is enabled for testing:

var io = require('socket.io')(80);

Registration event

io.on('connection', function (socket) {
    socket.on('disconnect', function () {

    })
})

connectionThe event is triggered when the client successfully connects to the server. With this event, we can know the information of the user connecting to the server at any time.

When the client successfully establishes the connectionconnectionIn the callback function of the event, we can stillsocketRegister some common events, such as the disconnect event, which is triggered when the client connection is disconnected, and then I know that the user has left.

Start service

So far, we have built the simplest onesocketServer, in order to be able to access our services in the browser, we also need to build a simple serverweb serverTo enable browsers to access our client pages.

For convenience, we choosenode.jsCommonly used inExpress frameworkTo achieveWeb services, examples are as follows:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.status(200).send('成功连接!')
});
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function (socket) {

});
server.listen(80);

Client reference

After the server is built, let’s take a look at how the client should be used.

After the server runs, it will dynamically generate the socket.io client js file in the root directory. the client can add a reference through a fixed path/socket. io/socket. io.js.

First, add a web page index.html and refer to the client js file in the web page:

<script src="//cdn.bootcss.com/socket.io/2.0.2/socket.io.js"></script>

Connection service

When the client successfully loads the socket.io client file, it will acquire a global object io, and we will initiate a connection request to the server through io.connect function.

var socket = io.connect('/');
socket.on('connect',function(){
    //连接成功
});
socket.on('disconnect',function(data){
    //连接断开
});

connectFunction can accept aUrl parameters, urls canHttp full address of socket service, can also beRelative path, if omitted, indicates the current path of the default connection. Similar to the server, the client also needs to register corresponding events to capture information, except thatThe successful client connection event is connect.

After learning how to use the client, let’s create a web pageindex.html, and add the following (save):

<html>
<head>
    <script src="//cdn.bootcss.com/socket.io/2.0.2/socket.io.js"></script>
    <script>
        window.onload = function(){
            var socket = io.connect('/');
            socket.on('connect',function(){
                document.write('连接成功!');
            });
        };
    </script>
</head>
<body>
</body>
</html>

After the page is added, remember to add it to the serverapp.jsAdd a route to it in so that we can visit the test web page:

app.get('/index',function(req,res){
   res.sendFile('index.html',{root:__dirname});
});

Real-time communication

Both the server and the client are finished, and the message will be sent.

When we successfully establish the connection, we can passSocket objectTheSend functionTo send messages to each other, for example-the client sends messages to the server (index.html):

var socket = io.connect('/');
socket.on('connect',function(){
   //客户端连接成功后发送消息'hello world!'
   socket.send('hello world!');
});
socket.on('message',function(data){
   alert(data);
});

After the connection is successful, we send a message to the serverhello world!, also forsocketRegisteredMessage event, it isSend functionFor the corresponding event of receiving message, when the server sends the message to the client, we can send the message to the client atmessageThe message sent was received in the event.

The server can also send messages to the client throughsendThe server sends a message to the client (app.js):

var io = require('scoket.io');
io.on('connection', function (socket) {
    socket.send('Hello World!');
    socket.on('message', function (data) {
        console.log(data);
    })
});

Like the client, the server needs to besocketregisteredMessage eventTo receive the message sent by the client.

Send information

socket.ioSince it is used for communication, how to send and receive information is fundamental.

Insocket.ioChina,Emit functionbe used fortxdWe usesendThe way to realize the exchange of information, in factSend functionJust ..Emit packagingIn fact, emit is still used, and see how the send function is implemented:

function send(){
  var args = toArray(arguments);
  args.unshift('message');
  this.emit.apply(this, args);
  return this;
}

InSend function, the original parameter is obtained and a parameter is inserted on the original basismessageAnd then called theEmit function. viasendThe implementation of the function, we also learned the use of emit function, it has multiple parameters,The first parameter is the event name, register the event at the receiving end to receive the information sent in the past. The name of the event can be defined freely. In different scenarios, we can define different events to receive the message.The second parameter is the data sent. After understanding the working principle, let’s replace send with emit function to send information:

//app.js
io.on('connection',function(socket){
     socket.emit('message','连接成功!');
     socket.on('message',function(data){
    });
});

Server event

Event monitoring is the basis of communication, so it is very important to fully understand socket.io events and learn how to use them at the right time. In some key states, socket.io can register corresponding events. Through event monitoring, we can respond to these events. Common events are as follows:

  • connection-The client successfully connected to the server.

  • message-capture clientsendInformation. .

  • disconnect-client disconnected.

  • error-An error has occurred.

Client

Compared with the server, the client provides more monitoring events. In real-time applications, we can register monitoring and respond to these events, for example:connectPrompts the user to connect successfully.disconnectPrompt the user to stop the service, etc.

  • connection-Successfully connected to the server.

  • connecting-Connecting.

  • disconnect-Disconnect.

  • connect_failed-Connection failed.

  • error-wrong connection.

  • message-Monitor the information send by the server.

  • reconnect_failed-reconnection failed.

  • reconnect-The reconnection was successful.

  • reconnecting-is reconnecting.

Then the clientsocketWhat is the sequence of initiating the connection? When connecting for the first time, the event triggering sequence is:connectingconnect;

When the connection is lost, the event triggering sequence is:disconnect → reconnecting → connecting → reconnect → connect.

Namespace

Namespace is really a very useful function. We can divide different rooms through namespaces. Broadcasting and communication in the room will not affect clients outside the room.

So how do you create a room? On the server side, throughof("")To divide the new namespace:

io.of('chat').on('connection',function(socket){
});

In the example, we create a file calledchat, the client can connect to the specified room through the following methods:

var socket = io.connect('/chat');

Although connected to the designated room, we can also operate on the server and enter and leave the room freely:

socket.join('chat');//进入chat房间
socket.leave('chat');//离开chat房间

Broadcast message

In real-time applications, broadcasting is an indispensable function. socket.io provides two server-side broadcasting methods.

The first broadcasting method can be called’Global broadcastAs the name implies, global broadcast is the information that all clients connected to the server will receive broadcast:

socket.broadcast.emit('DATA',data);

However, in the actual application scenario, we do not need all users to receive broadcast information, and some broadcast information is only sent to some clients, such as users in a certain room, then the following methods can be used:

socket.broadcast.to('chat').emit('DATA',data);

Middleware

socket.ioProviding middleware functions, we can preprocess requests through middleware, such as authentication:

io.use(function(socket, next){
  if (socket.request.headers.cookie) return next();
  next(new Error('Authentication error'));
});

The example shows authentication through middleware, when there is nocookieThrows an exception when.

pass parameter

In many application scenarios, clients need to pass parameters when initiating connection requests, which may beAuthentication, initialization settingsWait, thensocket.ioHow do I pass parameters when initiating a connection?

var socket = io.connect('/');

Due toConnect functionThe parameter that initiates the connection is aurl, you may think of stitching parameters to the url, such ashttp://xxxx? xx=xxxx, but unfortunately this is not feasible, we can pass parameters in this way:

var socket = io.connect('/',{ _query:'sid=123456' });

At the server side, the passed parameters can be obtained as follows:

io.use(function(socket){
     var query = socket.request._query;
     var sid = query.sid; 
});

The parameter passed by the client has been parsed into aJson objectThis object is_query.