Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. # Engine.IO: the realtime engine
  2. [![Build Status](https://github.com/socketio/engine.io/workflows/CI/badge.svg?branch=master))](https://github.com/socketio/engine.io/actions)
  3. [![NPM version](https://badge.fury.io/js/engine.io.svg)](http://badge.fury.io/js/engine.io)
  4. `Engine.IO` is the implementation of transport-based
  5. cross-browser/cross-device bi-directional communication layer for
  6. [Socket.IO](http://github.com/socketio/socket.io).
  7. ## How to use
  8. ### Server
  9. #### (A) Listening on a port
  10. ```js
  11. const engine = require('engine.io');
  12. const server = engine.listen(80);
  13. server.on('connection', socket => {
  14. socket.send('utf 8 string');
  15. socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
  16. });
  17. ```
  18. #### (B) Intercepting requests for a http.Server
  19. ```js
  20. const engine = require('engine.io');
  21. const http = require('http').createServer().listen(3000);
  22. const server = engine.attach(http);
  23. server.on('connection', socket => {
  24. socket.on('message', data => { });
  25. socket.on('close', () => { });
  26. });
  27. ```
  28. #### (C) Passing in requests
  29. ```js
  30. const engine = require('engine.io');
  31. const server = new engine.Server();
  32. server.on('connection', socket => {
  33. socket.send('hi');
  34. });
  35. // …
  36. httpServer.on('upgrade', (req, socket, head) => {
  37. server.handleUpgrade(req, socket, head);
  38. });
  39. httpServer.on('request', (req, res) => {
  40. server.handleRequest(req, res);
  41. });
  42. ```
  43. ### Client
  44. ```html
  45. <script src="/path/to/engine.io.js"></script>
  46. <script>
  47. const socket = new eio.Socket('ws://localhost/');
  48. socket.on('open', () => {
  49. socket.on('message', data => {});
  50. socket.on('close', () => {});
  51. });
  52. </script>
  53. ```
  54. For more information on the client refer to the
  55. [engine-client](http://github.com/socketio/engine.io-client) repository.
  56. ## What features does it have?
  57. - **Maximum reliability**. Connections are established even in the presence of:
  58. - proxies and load balancers.
  59. - personal firewall and antivirus software.
  60. - for more information refer to **Goals** and **Architecture** sections
  61. - **Minimal client size** aided by:
  62. - lazy loading of flash transports.
  63. - lack of redundant transports.
  64. - **Scalable**
  65. - load balancer friendly
  66. - **Future proof**
  67. - **100% Node.JS core style**
  68. - No API sugar (left for higher level projects)
  69. - Written in readable vanilla JavaScript
  70. ## API
  71. ### Server
  72. <hr><br>
  73. #### Top-level
  74. These are exposed by `require('engine.io')`:
  75. ##### Events
  76. - `flush`
  77. - Called when a socket buffer is being flushed.
  78. - **Arguments**
  79. - `Socket`: socket being flushed
  80. - `Array`: write buffer
  81. - `drain`
  82. - Called when a socket buffer is drained
  83. - **Arguments**
  84. - `Socket`: socket being flushed
  85. ##### Properties
  86. - `protocol` _(Number)_: protocol revision number
  87. - `Server`: Server class constructor
  88. - `Socket`: Socket class constructor
  89. - `Transport` _(Function)_: transport constructor
  90. - `transports` _(Object)_: map of available transports
  91. ##### Methods
  92. - `()`
  93. - Returns a new `Server` instance. If the first argument is an `http.Server` then the
  94. new `Server` instance will be attached to it. Otherwise, the arguments are passed
  95. directly to the `Server` constructor.
  96. - **Parameters**
  97. - `http.Server`: optional, server to attach to.
  98. - `Object`: optional, options object (see `Server#constructor` api docs below)
  99. The following are identical ways to instantiate a server and then attach it.
  100. ```js
  101. const httpServer; // previously created with `http.createServer();` from node.js api.
  102. // create a server first, and then attach
  103. const eioServer = require('engine.io').Server();
  104. eioServer.attach(httpServer);
  105. // or call the module as a function to get `Server`
  106. const eioServer = require('engine.io')();
  107. eioServer.attach(httpServer);
  108. // immediately attach
  109. const eioServer = require('engine.io')(httpServer);
  110. // with custom options
  111. const eioServer = require('engine.io')(httpServer, {
  112. maxHttpBufferSize: 1e3
  113. });
  114. ```
  115. - `listen`
  116. - Creates an `http.Server` which listens on the given port and attaches WS
  117. to it. It returns `501 Not Implemented` for regular http requests.
  118. - **Parameters**
  119. - `Number`: port to listen on.
  120. - `Object`: optional, options object
  121. - `Function`: callback for `listen`.
  122. - **Options**
  123. - All options from `Server.attach` method, documented below.
  124. - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
  125. - **Returns** `Server`
  126. ```js
  127. const engine = require('engine.io');
  128. const server = engine.listen(3000, {
  129. pingTimeout: 2000,
  130. pingInterval: 10000
  131. });
  132. server.on('connection', /* ... */);
  133. ```
  134. - `attach`
  135. - Captures `upgrade` requests for a `http.Server`. In other words, makes
  136. a regular http.Server WebSocket-compatible.
  137. - **Parameters**
  138. - `http.Server`: server to attach to.
  139. - `Object`: optional, options object
  140. - **Options**
  141. - All options from `Server.attach` method, documented below.
  142. - **Additionally** See Server `constructor` below for options you can pass for creating the new Server
  143. - **Returns** `Server` a new Server instance.
  144. ```js
  145. const engine = require('engine.io');
  146. const httpServer = require('http').createServer().listen(3000);
  147. const server = engine.attach(httpServer, {
  148. wsEngine: require('eiows').Server // requires having eiows as dependency
  149. });
  150. server.on('connection', /* ... */);
  151. ```
  152. #### Server
  153. The main server/manager. _Inherits from EventEmitter_.
  154. ##### Events
  155. - `connection`
  156. - Fired when a new connection is established.
  157. - **Arguments**
  158. - `Socket`: a Socket object
  159. - `initial_headers`
  160. - Fired on the first request of the connection, before writing the response headers
  161. - **Arguments**
  162. - `headers` (`Object`): a hash of headers
  163. - `req` (`http.IncomingMessage`): the request
  164. - `headers`
  165. - Fired on the all requests of the connection, before writing the response headers
  166. - **Arguments**
  167. - `headers` (`Object`): a hash of headers
  168. - `req` (`http.IncomingMessage`): the request
  169. - `connection_error`
  170. - Fired when an error occurs when establishing the connection.
  171. - **Arguments**
  172. - `error`: an object with following properties:
  173. - `req` (`http.IncomingMessage`): the request that was dropped
  174. - `code` (`Number`): one of `Server.errors`
  175. - `message` (`string`): one of `Server.errorMessages`
  176. - `context` (`Object`): extra info about the error
  177. | Code | Message |
  178. | ---- | ------- |
  179. | 0 | "Transport unknown"
  180. | 1 | "Session ID unknown"
  181. | 2 | "Bad handshake method"
  182. | 3 | "Bad request"
  183. | 4 | "Forbidden"
  184. | 5 | "Unsupported protocol version"
  185. ##### Properties
  186. **Important**: if you plan to use Engine.IO in a scalable way, please
  187. keep in mind the properties below will only reflect the clients connected
  188. to a single process.
  189. - `clients` _(Object)_: hash of connected clients by id.
  190. - `clientsCount` _(Number)_: number of connected clients.
  191. ##### Methods
  192. - **constructor**
  193. - Initializes the server
  194. - **Parameters**
  195. - `Object`: optional, options object
  196. - **Options**
  197. - `pingTimeout` (`Number`): how many ms without a pong packet to
  198. consider the connection closed (`20000`)
  199. - `pingInterval` (`Number`): how many ms before sending a new ping
  200. packet (`25000`)
  201. - `upgradeTimeout` (`Number`): how many ms before an uncompleted transport upgrade is cancelled (`10000`)
  202. - `maxHttpBufferSize` (`Number`): how many bytes or characters a message
  203. can be, before closing the session (to avoid DoS). Default
  204. value is `1E6`.
  205. - `allowRequest` (`Function`): A function that receives a given handshake
  206. or upgrade request as its first parameter, and can decide whether to
  207. continue or not. The second argument is a function that needs to be
  208. called with the decided information: `fn(err, success)`, where
  209. `success` is a boolean value where false means that the request is
  210. rejected, and err is an error code.
  211. - `transports` (`<Array> String`): transports to allow connections
  212. to (`['polling', 'websocket']`)
  213. - `allowUpgrades` (`Boolean`): whether to allow transport upgrades
  214. (`true`)
  215. - `perMessageDeflate` (`Object|Boolean`): parameters of the WebSocket permessage-deflate extension
  216. (see [ws module](https://github.com/einaros/ws) api docs). Set to `true` to enable. (defaults to `false`)
  217. - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
  218. - `httpCompression` (`Object|Boolean`): parameters of the http compression for the polling transports
  219. (see [zlib](http://nodejs.org/api/zlib.html#zlib_options) api docs). Set to `false` to disable. (`true`)
  220. - `threshold` (`Number`): data is compressed only if the byte size is above this value (`1024`)
  221. - `cookie` (`Object|Boolean`): configuration of the cookie that
  222. contains the client sid to send as part of handshake response
  223. headers. This cookie might be used for sticky-session. Defaults to not sending any cookie (`false`).
  224. See [here](https://github.com/jshttp/cookie#options-1) for all supported options.
  225. - `wsEngine` (`Function`): what WebSocket server implementation to use. Specified module must conform to the `ws` interface (see [ws module api docs](https://github.com/websockets/ws/blob/master/doc/ws.md)). Default value is `ws`. An alternative c++ addon is also available by installing `eiows` module.
  226. - `cors` (`Object`): the options that will be forwarded to the cors module. See [there](https://github.com/expressjs/cors#configuration-options) for all available options. Defaults to no CORS allowed.
  227. - `initialPacket` (`Object`): an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
  228. - `allowEIO3` (`Boolean`): whether to support v3 Engine.IO clients (defaults to `false`)
  229. - `close`
  230. - Closes all clients
  231. - **Returns** `Server` for chaining
  232. - `handleRequest`
  233. - Called internally when a `Engine` request is intercepted.
  234. - **Parameters**
  235. - `http.IncomingMessage`: a node request object
  236. - `http.ServerResponse`: a node response object
  237. - **Returns** `Server` for chaining
  238. - `handleUpgrade`
  239. - Called internally when a `Engine` ws upgrade is intercepted.
  240. - **Parameters** (same as `upgrade` event)
  241. - `http.IncomingMessage`: a node request object
  242. - `net.Stream`: TCP socket for the request
  243. - `Buffer`: legacy tail bytes
  244. - **Returns** `Server` for chaining
  245. - `attach`
  246. - Attach this Server instance to an `http.Server`
  247. - Captures `upgrade` requests for a `http.Server`. In other words, makes
  248. a regular http.Server WebSocket-compatible.
  249. - **Parameters**
  250. - `http.Server`: server to attach to.
  251. - `Object`: optional, options object
  252. - **Options**
  253. - `path` (`String`): name of the path to capture (`/engine.io`).
  254. - `destroyUpgrade` (`Boolean`): destroy unhandled upgrade requests (`true`)
  255. - `destroyUpgradeTimeout` (`Number`): milliseconds after which unhandled requests are ended (`1000`)
  256. - `generateId`
  257. - Generate a socket id.
  258. - Overwrite this method to generate your custom socket id.
  259. - **Parameters**
  260. - `http.IncomingMessage`: a node request object
  261. - **Returns** A socket id for connected client.
  262. <hr><br>
  263. #### Socket
  264. A representation of a client. _Inherits from EventEmitter_.
  265. ##### Events
  266. - `close`
  267. - Fired when the client is disconnected.
  268. - **Arguments**
  269. - `String`: reason for closing
  270. - `Object`: description object (optional)
  271. - `message`
  272. - Fired when the client sends a message.
  273. - **Arguments**
  274. - `String` or `Buffer`: Unicode string or Buffer with binary contents
  275. - `error`
  276. - Fired when an error occurs.
  277. - **Arguments**
  278. - `Error`: error object
  279. - `flush`
  280. - Called when the write buffer is being flushed.
  281. - **Arguments**
  282. - `Array`: write buffer
  283. - `drain`
  284. - Called when the write buffer is drained
  285. - `packet`
  286. - Called when a socket received a packet (`message`, `ping`)
  287. - **Arguments**
  288. - `type`: packet type
  289. - `data`: packet data (if type is message)
  290. - `packetCreate`
  291. - Called before a socket sends a packet (`message`, `ping`)
  292. - **Arguments**
  293. - `type`: packet type
  294. - `data`: packet data (if type is message)
  295. - `heartbeat`
  296. - Called when `ping` or `pong` packed is received (depends of client version)
  297. ##### Properties
  298. - `id` _(String)_: unique identifier
  299. - `server` _(Server)_: engine parent reference
  300. - `request` _(http.IncomingMessage)_: request that originated the Socket
  301. - `upgraded` _(Boolean)_: whether the transport has been upgraded
  302. - `readyState` _(String)_: opening|open|closing|closed
  303. - `transport` _(Transport)_: transport reference
  304. ##### Methods
  305. - `send`:
  306. - Sends a message, performing `message = toString(arguments[0])` unless
  307. sending binary data, which is sent as is.
  308. - **Parameters**
  309. - `String` | `Buffer` | `ArrayBuffer` | `ArrayBufferView`: a string or any object implementing `toString()`, with outgoing data, or a Buffer or ArrayBuffer with binary data. Also any ArrayBufferView can be sent as is.
  310. - `Object`: optional, options object
  311. - `Function`: optional, a callback executed when the message gets flushed out by the transport
  312. - **Options**
  313. - `compress` (`Boolean`): whether to compress sending data. This option might be ignored and forced to be `true` when using polling. (`true`)
  314. - **Returns** `Socket` for chaining
  315. - `close`
  316. - Disconnects the client
  317. - **Returns** `Socket` for chaining
  318. ### Client
  319. <hr><br>
  320. Exposed in the `eio` global namespace (in the browser), or by
  321. `require('engine.io-client')` (in Node.JS).
  322. For the client API refer to the
  323. [engine-client](http://github.com/learnboost/engine.io-client) repository.
  324. ## Debug / logging
  325. Engine.IO is powered by [debug](http://github.com/visionmedia/debug).
  326. In order to see all the debug output, run your app with the environment variable
  327. `DEBUG` including the desired scope.
  328. To see the output from all of Engine.IO's debugging scopes you can use:
  329. ```
  330. DEBUG=engine* node myapp
  331. ```
  332. ## Transports
  333. - `polling`: XHR / JSONP polling transport.
  334. - `websocket`: WebSocket transport.
  335. ## Plugins
  336. - [engine.io-conflation](https://github.com/EugenDueck/engine.io-conflation): Makes **conflation and aggregation** of messages straightforward.
  337. ## Support
  338. The support channels for `engine.io` are the same as `socket.io`:
  339. - irc.freenode.net **#socket.io**
  340. - [Google Groups](http://groups.google.com/group/socket_io)
  341. - [Website](http://socket.io)
  342. ## Development
  343. To contribute patches, run tests or benchmarks, make sure to clone the
  344. repository:
  345. ```
  346. git clone git://github.com/LearnBoost/engine.io.git
  347. ```
  348. Then:
  349. ```
  350. cd engine.io
  351. npm install
  352. ```
  353. ## Tests
  354. Tests run with `npm test`. It runs the server tests that are aided by
  355. the usage of `engine.io-client`.
  356. Make sure `npm install` is run first.
  357. ## Goals
  358. The main goal of `Engine` is ensuring the most reliable realtime communication.
  359. Unlike the previous Socket.IO core, it always establishes a long-polling
  360. connection first, then tries to upgrade to better transports that are "tested" on
  361. the side.
  362. During the lifetime of the Socket.IO projects, we've found countless drawbacks
  363. to relying on `HTML5 WebSocket` or `Flash Socket` as the first connection
  364. mechanisms.
  365. Both are clearly the _right way_ of establishing a bidirectional communication,
  366. with HTML5 WebSocket being the way of the future. However, to answer most business
  367. needs, alternative traditional HTTP 1.1 mechanisms are just as good as delivering
  368. the same solution.
  369. WebSocket based connections have two fundamental benefits:
  370. 1. **Better server performance**
  371. - _A: Load balancers_<br>
  372. Load balancing a long polling connection poses a serious architectural nightmare
  373. since requests can come from any number of open sockets by the user agent, but
  374. they all need to be routed to the process and computer that owns the `Engine`
  375. connection. This negatively impacts RAM and CPU usage.
  376. - _B: Network traffic_<br>
  377. WebSocket is designed around the premise that each message frame has to be
  378. surrounded by the least amount of data. In HTTP 1.1 transports, each message
  379. frame is surrounded by HTTP headers and chunked encoding frames. If you try to
  380. send the message _"Hello world"_ with xhr-polling, the message ultimately
  381. becomes larger than if you were to send it with WebSocket.
  382. - _C: Lightweight parser_<br>
  383. As an effect of **B**, the server has to do a lot more work to parse the network
  384. data and figure out the message when traditional HTTP requests are used
  385. (as in long polling). This means that another advantage of WebSocket is
  386. less server CPU usage.
  387. 2. **Better user experience**
  388. Due to the reasons stated in point **1**, the most important effect of being able
  389. to establish a WebSocket connection is raw data transfer speed, which translates
  390. in _some_ cases in better user experience.
  391. Applications with heavy realtime interaction (such as games) will benefit greatly,
  392. whereas applications like realtime chat (Gmail/Facebook), newsfeeds (Facebook) or
  393. timelines (Twitter) will have negligible user experience improvements.
  394. Having said this, attempting to establish a WebSocket connection directly so far has
  395. proven problematic:
  396. 1. **Proxies**<br>
  397. Many corporate proxies block WebSocket traffic.
  398. 2. **Personal firewall and antivirus software**<br>
  399. As a result of our research, we've found that at least 3 personal security
  400. applications block WebSocket traffic.
  401. 3. **Cloud application platforms**<br>
  402. Platforms like Heroku or No.de have had trouble keeping up with the fast-paced
  403. nature of the evolution of the WebSocket protocol. Applications therefore end up
  404. inevitably using long polling, but the seamless installation experience of
  405. Socket.IO we strive for (_"require() it and it just works"_) disappears.
  406. Some of these problems have solutions. In the case of proxies and personal programs,
  407. however, the solutions many times involve upgrading software. Experience has shown
  408. that relying on client software upgrades to deliver a business solution is
  409. fruitless: the very existence of this project has to do with a fragmented panorama
  410. of user agent distribution, with clients connecting with latest versions of the most
  411. modern user agents (Chrome, Firefox and Safari), but others with versions as low as
  412. IE 5.5.
  413. From the user perspective, an unsuccessful WebSocket connection can translate in
  414. up to at least 10 seconds of waiting for the realtime application to begin
  415. exchanging data. This **perceptively** hurts user experience.
  416. To summarize, **Engine** focuses on reliability and user experience first, marginal
  417. potential UX improvements and increased server performance second. `Engine` is the
  418. result of all the lessons learned with WebSocket in the wild.
  419. ## Architecture
  420. The main premise of `Engine`, and the core of its existence, is the ability to
  421. swap transports on the fly. A connection starts as xhr-polling, but it can
  422. switch to WebSocket.
  423. The central problem this poses is: how do we switch transports without losing
  424. messages?
  425. `Engine` only switches from polling to another transport in between polling
  426. cycles. Since the server closes the connection after a certain timeout when
  427. there's no activity, and the polling transport implementation buffers messages
  428. in between connections, this ensures no message loss and optimal performance.
  429. Another benefit of this design is that we workaround almost all the limitations
  430. of **Flash Socket**, such as slow connection times, increased file size (we can
  431. safely lazy load it without hurting user experience), etc.
  432. ## FAQ
  433. ### Can I use engine without Socket.IO ?
  434. Absolutely. Although the recommended framework for building realtime applications
  435. is Socket.IO, since it provides fundamental features for real-world applications
  436. such as multiplexing, reconnection support, etc.
  437. `Engine` is to Socket.IO what Connect is to Express. An essential piece for building
  438. realtime frameworks, but something you _probably_ won't be using for building
  439. actual applications.
  440. ### Does the server serve the client?
  441. No. The main reason is that `Engine` is meant to be bundled with frameworks.
  442. Socket.IO includes `Engine`, therefore serving two clients is not necessary. If
  443. you use Socket.IO, including
  444. ```html
  445. <script src="/socket.io/socket.io.js">
  446. ```
  447. has you covered.
  448. ### Can I implement `Engine` in other languages?
  449. Absolutely. The [engine.io-protocol](https://github.com/socketio/engine.io-protocol)
  450. repository contains the most up-to-date description of the specification
  451. at all times.
  452. ## License
  453. (The MIT License)
  454. Copyright (c) 2014 Guillermo Rauch &lt;guillermo@learnboost.com&gt;
  455. Permission is hereby granted, free of charge, to any person obtaining
  456. a copy of this software and associated documentation files (the
  457. 'Software'), to deal in the Software without restriction, including
  458. without limitation the rights to use, copy, modify, merge, publish,
  459. distribute, sublicense, and/or sell copies of the Software, and to
  460. permit persons to whom the Software is furnished to do so, subject to
  461. the following conditions:
  462. The above copyright notice and this permission notice shall be
  463. included in all copies or substantial portions of the Software.
  464. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  465. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  466. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  467. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  468. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  469. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  470. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.