{"id":13527146,"url":"https://github.com/sitegui/nodejs-websocket","last_synced_at":"2025-05-15T09:05:35.093Z","repository":{"id":9611392,"uuid":"11535817","full_name":"sitegui/nodejs-websocket","owner":"sitegui","description":"A node.js module for websocket server and client","archived":false,"fork":false,"pushed_at":"2023-08-30T12:03:39.000Z","size":101,"stargazers_count":739,"open_issues_count":18,"forks_count":154,"subscribers_count":33,"default_branch":"master","last_synced_at":"2025-04-11T16:32:58.069Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sitegui.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2013-07-19T19:46:11.000Z","updated_at":"2025-03-14T12:51:47.000Z","dependencies_parsed_at":"2024-01-13T07:33:01.549Z","dependency_job_id":"1a818085-7200-4b99-86ae-f220958531f7","html_url":"https://github.com/sitegui/nodejs-websocket","commit_stats":{"total_commits":59,"total_committers":10,"mean_commits":5.9,"dds":"0.30508474576271183","last_synced_commit":"e6a57ed49ba0f9c0196f046174ffe1e1bf5f8db0"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sitegui%2Fnodejs-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sitegui%2Fnodejs-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sitegui%2Fnodejs-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sitegui%2Fnodejs-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sitegui","download_url":"https://codeload.github.com/sitegui/nodejs-websocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248441351,"owners_count":21103977,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T06:01:42.062Z","updated_at":"2025-04-11T16:33:56.926Z","avatar_url":"https://github.com/sitegui.png","language":"JavaScript","readme":"# Nodejs Websocket\n[![Build Status](https://travis-ci.org/sitegui/nodejs-websocket.svg?branch=master)](https://travis-ci.org/sitegui/nodejs-websocket)\n[![Inline docs](https://inch-ci.org/github/sitegui/nodejs-websocket.svg?branch=master)](https://inch-ci.org/github/sitegui/nodejs-websocket)\n[![Dependency Status](https://david-dm.org/sitegui/nodejs-websocket.svg)](https://david-dm.org/sitegui/nodejs-websocket)\n\nA nodejs module for websocket server and client\n\n# How to use it\nInstall with `npm install nodejs-websocket` or put all files in a folder called \"nodejs-websocket\", and:\n```javascript\nvar ws = require(\"nodejs-websocket\")\n\n// Scream server example: \"hi\" -\u003e \"HI!!!\"\nvar server = ws.createServer(function (conn) {\n\tconsole.log(\"New connection\")\n\tconn.on(\"text\", function (str) {\n\t\tconsole.log(\"Received \"+str)\n\t\tconn.sendText(str.toUpperCase()+\"!!!\")\n\t})\n\tconn.on(\"close\", function (code, reason) {\n\t\tconsole.log(\"Connection closed\")\n\t})\n}).listen(8001)\n```\n\nSe other examples inside the folder samples\n\n# ws\nThe main object, returned by `require(\"nodejs-websocket\")`.\n\n## ws.createServer([options], [callback])\nReturns a new `Server` object.\n\nThe `options` is an optional object that will be handed to net.createServer() to create an ordinary socket.\nIf it has a property called \"secure\" with value `true`, tls.createServer() will be used instead.\n\nTo support protocols, the `options` object may have either of these properties:\n* `validProtocols`: an array of protocol names the server accepts. The server will pick the most preferred protocol in the client's list.\n* `selectProtocol`: a callback to resolve the protocol negotiation. This callback will be passed two parameters: the connection handling the handshake and the array of protocol names informed by the client, ordered by preference. It should return the resolved protocol, or empty if there is no agreement.\n\nThe `callback` is a function which is automatically added to the `\"connection\"` event.\n\n## ws.connect(URL, [options], [callback])\nReturns a new `Connection` object, representing a websocket client connection\n\n`URL` is a string with the format \"ws://localhost:8000/chat\" (the port can be omitted)\n\n`options` is an object that will be passed to net.connect() (or tls.connect() if the protocol is \"wss:\").\nThe properties \"host\" and \"port\" will be read from the `URL`.\nThe optional property `extraHeaders` will be used to add more headers to the HTTP handshake request. If present, it must be an object, like `{'X-My-Header': 'value'}`.\nThe optional property `protocols` will be used in the handshake (as \"Sec-WebSocket-Protocol\" header) to allow the server to choose one of those values. If present, it must be an array of strings.\n\n`callback` will be added as \"connect\" listener\n\n## ws.setBinaryFragmentation(bytes)\nSets the minimum size of a pack of binary data to send in a single frame (default: 512kiB)\n\n## ws.setMaxBufferLength(bytes)\nSet the maximum size the internal Buffer can grow (default: 2MiB)\nIf at any time it stays bigger than this, the connection will be closed with code 1009\nThis is a security measure, to avoid memory attacks\n\n# Server\nThe class that represents a websocket server, much like a HTTP server\n\n## server.listen(port, [host], [callback])\nStarts accepting connections on a given `port` and `host`.\n\nIf the `host` is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).\n\nA `port` value of zero will assign a random port.\n\n`callback` will be added as an listener for the `'listening'` event.\n\n## server.close([callback])\nStops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs.\n\n## server.socket\nThe underlying socket, returned by net.createServer or tls.createServer\n\n## server.connections\nAn Array with all connected clients. It's useful for broadcasting a message:\n```javascript\nfunction broadcast(server, msg) {\n\tserver.connections.forEach(function (conn) {\n\t\tconn.sendText(msg)\n\t})\n}\n```\n\n## Event: 'listening()'\nEmitted when the server has been bound after calling server.listen\n\n## Event: 'close()'\nEmitted when the server closes. Note that if connections exist, this event is not emitted until all connections are completely ended.\n\n## Event: 'error(errObj)'\nEmitted when an error occurs. The 'close' event will be called directly following this event.\n\n## Event: 'connection(conn)'\nEmitted when a new connection is made successfully (after the handshake have been completed). conn is an instance of Connection\n\n# Connection\nThe class that represents a connection, either a client-created (accepted by a nodejs ws server) or client connection.\nThe websocket protocol has two types of data frames: text and binary.\nText frames are implemented as simple send function and receive event.\nBinary frames are implemented as streams: when you receive binary data, you get a ReadableStream; to send binary data, you must ask for a WritableStream and write into it.\nThe binary data will be divided into frames and be sent over the socket.\n\nYou cannot send text data while sending binary data. If you try to do so, the connection will emit an \"error\" event\n\n## connection.sendText(str, [callback])\nSends a given string to the other side. You can't send text data in the middle of a binary transmission.\n\n`callback` will be added as a listener to write operation over the socket\n\n## connection.beginBinary()\nAsks the connection to begin transmitting binary data. Returns a WritableStream.\nThe binary transmission will end when the WritableStream finishes (like when you call .end on it)\n\n## connection.sendBinary(data, [callback])\nSends a single chunk of binary data (like calling connection.beginBinary().end(data))\n\n`callback` will be added as a listener to write operation over the socket\n\n## connection.send(data, [callback])\nSends a given string or Buffer to the other side. This is simply an alias for `sendText()` if data is a string or `sendBinary()` if the data is a Buffer.\n\n`callback` will be added as a listener to write operation over the socket\n\n## connection.sendPing([data=''])\nSends a [ping](http://tools.ietf.org/html/rfc6455#section-5.5.2) with optional payload\n\n## connection.close([code, [reason]])\nStarts the closing handshake (sends a close frame)\n\n## connection.socket\nThe underlying net or tls socket\n\n## connection.server\nIf the connection was accepted by a nodejs server, a reference to it will be saved here. null otherwise\n\n## connection.readyState\nOne of these constants, representing the current state of the connection. Only an open connection can be used to send/receive data.\n* connection.CONNECTING (waiting for handshake completion)\n* connection.OPEN\n* connection.CLOSING (waiting for the answer to a close frame)\n* connection.CLOSED\n\n## connection.outStream\nStores the OutStream object returned by connection.beginBinary(). null if there is no current binary data beeing sent.\n\n## connection.path\nFor a connection accepted by a server, it is a string representing the path to which the connection was made (example: \"/chat\"). null otherwise\n\n## connection.headers\nRead only map of header names and values. Header names are lower-cased\n\n## connection.protocols\nArray of protocols requested by the client. If no protocols were requested, it will be an empty array.\n\nAdditional resources on websocket subprotocols:\n* [WebSocket Subprotocol Name Registry](http://www.iana.org/assignments/websocket/websocket.xml#subprotocol-name)\n* [The WebSocket Protocol](https://tools.ietf.org/html/rfc6455#section-11.3.4)\n\n## connection.protocol\nThe protocol agreed for this connection, if any. It will be an element of `connection.protocols`.\n\n## Event: 'close(code, reason)'\nEmitted when the connection is closed by any side\n\n## Event: 'error(err)'\nEmitted in case of error (like trying to send text data while still sending binary data).\nIn case of an invalid handshake response will also be emited.\n\n## Event: 'text(str)'\nEmitted when a text is received. `str` is a string\n\n## Event: 'binary(inStream)'\nEmitted when the beginning of binary data is received. `inStream` is a [ReadableStream](https://nodejs.org/api/stream.html#stream_class_stream_readable):\n```javascript\nvar server = ws.createServer(function (conn) {\n\tconsole.log(\"New connection\")\n\tconn.on(\"binary\", function (inStream) {\n\t\t// Empty buffer for collecting binary data\n\t\tvar data = Buffer.alloc(0)\n\t\t// Read chunks of binary data and add to the buffer\n\t\tinStream.on(\"readable\", function () {\n\t\t    var newData = inStream.read()\n\t\t    if (newData)\n\t\t        data = Buffer.concat([data, newData], data.length+newData.length)\n\t\t})\n\t\tinStream.on(\"end\", function () {\n\t\t\tconsole.log(\"Received \" + data.length + \" bytes of binary data\")\n\t\t    process_my_data(data)\n\t\t})\n\t})\n\tconn.on(\"close\", function (code, reason) {\n\t\tconsole.log(\"Connection closed\")\n\t})\n}).listen(8001)\n```\n\n## Event: 'connect()'\nEmitted when the connection is fully established (after the handshake)\n\n## Event: 'pong(data)'\nEmitted when a [pong](http://tools.ietf.org/html/rfc6455#section-5.5.3) is received, usually after a ping was sent. `data` is the pong payload, as a string\n","funding_links":[],"categories":["Repository","JavaScript","miscellaneous","Tools per Language","Others"],"sub_categories":["Real-time","Node.js"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsitegui%2Fnodejs-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsitegui%2Fnodejs-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsitegui%2Fnodejs-websocket/lists"}