Brief introduction
As we all know, websocket mainly through the browser and server to establish a long connection, and then achieve the mutual data communication. Unlike HTTP polling, it does not have a large number of invalid HTTP message exchanges, thus saving money. WebSocket is actually a dual-channel TCP connection.
Obviously, the whole work is divided into two steps: Creating a connection and sending data. So how is the connection built? In fact, only need to do a handshake on the browser and server side of the action can be. And this handshake is actually an HTTP request, but the next work is not OK with HTTP.
The handshake request message is roughly the following:
GET /chat HTTP/1.1Host: example.com:8000Upgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13
The response message is roughly the following:
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The upgrade header inside HTTP represents the switch from the HTTP protocol to another protocol, or the replacement of a different version of HTTP. Sec-websocket-key and Sec-websocket-accept are the fields used for validation. The latter is calculated by a series of operations, which is used to determine whether the response and the request match the client.
Using Websocket-node
First, let's experience the use of the library "Websocket-node".
In fact, using this library is to create a websocket-server, in app.js, we can create.
varPort = 3001;varWebsocketserver = require (' WebSocket ')). server;varHTTP = require (' http ');//Create HttpservervarHttpserver =http.createserver (); Httpserver.listen (Port,function() {Console.log (NewDate () + "Http Server is listening" +( port);});//Create WebsocketservervarWSServer =Newwebsocketserver ({httpserver:httpserver}); Wsserver.on (' Request ',function(Request) {Console.log (NewDate () + "connection from Origin:" + Request.origin + '. '); //Establish a connection varConnection = request.accept (' example '), Request.origin); //send a message to the clientConnection.sendutf ("Connection from" +request.origin); Connection.on (' Close ',function() {Console.log (connection.remoteaddress+ "Disconnected."); }) //Receive MessageConnection.on (' message ',function(message) {Try{Connection.sendutf ("Server accpected:" +message.utf8data); }Catch(e) {}})})
In the browser, it has nothing to do with this library, directly with the browser-supported API to create WebSocket client, send and receive messages.
varWSServer = "ws://localhost:3001";varWS =NewWebSocket (WSServer, ' example ')); Ws.onopen=function(e) {varmsg = "Hello server!"; Ws.send (msg)&&print (msg);} Ws.onclose=function(e) {varmsg = "Closed Connection"; Print (msg);} Ws.onmessage=function(e) {varmsg = "Received:" +E.data; Print (msg);}
SOURCE parsing
Source has multiple files, we only focus on websocketserver.js, address
First, in the incoming configuration, you must bind a httpserver for the handshake. When a client establishes a connection, a handshake is initiated and the server's upgrade event is triggered to go to the service-side processing function. In this function, a Wsrequest object is created and sent as a parameter to the request event. Next, according to the client's accept situation to enter into the handlerequestaccepted, the next connect event will be triggered.
varUpgradehandler = This. _handlers.upgrade; This. Config.httpServer.forEach (function(httpserver) {Httpserver.on (' Upgrade ', Upgradehandler);}); Handleupgrade:varWsrequest =NewWebsocketrequest (socket, request, This. config);Try{wsrequest.readhandshake ();} Wsrequest.once (' Requestaccepted ', This. _handlers.requestaccepted); Wsrequest.once (' Requestresolved ', This. _handlers.requestresolved);if(! This. config.autoacceptconnections && Utils.eventemitterlistenercount ( This, ' request ') > 0) { This. Emit (' request ', wsrequest);} Handlerequestaccepted: This. Connections.push (connection); This. Emit (' Connect ', connection);
In addition, Websocketserver inherits the Eventemitter, so it has the ability to handle events:
Util.inherits (Websocketserver, Eventemitter);
Every day to see a piece of code series (ii): Websocket-node