官术网_书友最值得收藏!

  • Socket.IO Cookbook
  • Tyson Cadenhead
  • 730字
  • 2021-07-09 21:49:09

Introduction

Socket.IO is a powerful tool for creating real-time applications with bidirectional communication between the server side and the client side. It leverages the power of WebSockets along with several fallbacks, including JSON long polling and JSONP long polling through a single unified API. It can be used to create bidirectional interactions, such as real-time dashboards, chat applications, and multiplayer games.

In my previous jobs, I created several real-time JavaScript dashboards predating the Socket.IO library. During that time, I felt the pain of not having a good solution for true real-time communication. I found myself using hacks to obtain new data from the user interface. One method was to pound the server with an Ajax call every few seconds. The server had no way of knowing whether anything had updated since the last request, so it would dump all the data into the huge JSON object. It was up to the client-side JavaScript application to search the data and check whether there were any updates. If there were updates, the client side was responsible for updating the display as needed. This turned out to be difficult to maintain and a nightmare to debug. When Socket.IO was released, I was blown away. Now, I could send only the pieces of data that had actually been updated from the server instead of pushing up everything. Instead of setting an interval to make Ajax calls, I could just send data when new data came in. In short, Socket.IO made my life easier.

Socket.IO is an open source library created by Guillermo Rauch. It is built with Engine.IO, which is a lower-level abstraction on top of the WebSocket technology. Socket.IO is used to communicate bidirectionally between the server side and the client side in a syntax that looks as if you are just triggering and listening to events. The WebSocket API protocol was standardized in 2011. It is a Transmission Control Protocol (TCP) that only relies on HTTP for its initial handshake. After the handshake is complete, the connection is left open so that the server and the client can pass messages back and forth as needed.

For reference, a typical WebSocket connection without Socket.IO will look something similar to the following code on the client side:

Note

We are not falling back for browsers that do not support WebSockets.

if ('Websocket' in window) {
    var ws = new WebSocket('ws://localhost:5000/channel');
    
    ws.onopen = function () {
        ws.send('Hello world');
    };
    
    ws.onmessage = function (e) {
        console.log(e.data);
    };
    
    ws.onclose = function () {
        console.warn('WebSocket disconnected');
    }

} else {
    throw new Error('This browser does not support websockets');
}

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Socket.IO goes a step beyond just providing an easy-to-use and more robust API on top of WebSockets. It also provides the ability to seamlessly use other real-time protocols if WebSockets are not available. For example, it will fall back on JSON long polling in the absence of WebSocket support. Long polling is essentially a trick to emulate the WebSocket behavior in browsers that don't support WebSockets. After a long polling request is made, it is held onto by the server instead of immediately responding as a traditional HTTP request would. When data becomes available, the long polling request is resolved, closing the loop of the long request cycle. At this point, a new long polling request will typically be made. This gives the illusion of the continuous connection that WebSockets provides. Although long polling is less than ideal in the landscape of modern technology, it is a perfect fallback when needed. When you send a message with Socket.IO, the API for WebSockets and long polling are identical, so you don't have to deal with the mental overhead of integrating two syntactically different technologies.

Although there are Socket.IO implementations in many server-side languages, we will use Node.js in this book. With Node.js, we can write JavaScript on the server side, which gives us a single syntax on the server and client.

In this chapter, we will create a Node server with Socket.IO and obtain some very basic cross-browser messaging working. We will also look at debugging tools that make working with Socket.IO even easier.

主站蜘蛛池模板: 精河县| 星子县| 临湘市| 北碚区| 静海县| 泉州市| 开化县| 封丘县| 南阳市| 雷波县| 湄潭县| 镇远县| 万年县| 沂水县| 三门峡市| 上林县| 金寨县| 延寿县| 吴堡县| 双流县| 辉南县| 合作市| 栾川县| 镇安县| 柘荣县| 乌鲁木齐市| 丹巴县| 青铜峡市| 百色市| 汾西县| 汝州市| 庄浪县| 五常市| 赣州市| 丹棱县| 沙雅县| 扎鲁特旗| 东兰县| 波密县| 清苑县| 乐平市|