1. 程式人生 > >node.js ws模組 方法屬性(websocket)

node.js ws模組 方法屬性(websocket)

WebSocket compression

ws supports the permessage-deflate extension which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message.

The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed.

The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the perMessageDeflate option to false.

const WebSocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path', {
  perMessageDeflate: false
});

Usage examples

Sending and receiving text data

const WebSocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  ws.send('something');
});

ws.on('message', function incoming(data) {
  console.log(data);
});

Sending binary data

const WebSocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  const array = new Float32Array(5);

  for (var i = 0; i < array.length; ++i) {
    array[i] = i / 2;
  }

  ws.send(array);
});

Server example

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

Broadcast example

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

// Broadcast to all.
wss.broadcast = function broadcast(data) {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  });
};

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    // Broadcast to everyone else.
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
});

ExpressJS example

const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');

const app = express();

app.use(function (req, res) {
  res.send({ msg: "hello" });
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws, req) {
  const location = url.parse(req.url, true);
  // You might use location.query.access_token to authenticate or share sessions
  // or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312)

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

server.listen(8080, function listening() {
  console.log('Listening on %d', server.address().port);
});

echo.websocket.org demo

const WebSocket = require('ws');

const ws = new WebSocket('wss://echo.websocket.org/', {
  origin: 'https://websocket.org'
});

ws.on('open', function open() {
  console.log('connected');
  ws.send(Date.now());
});

ws.on('close', function close() {
  console.log('disconnected');
});

ws.on('message', function incoming(data) {
  console.log(`Roundtrip time: ${Date.now() - data} ms`);

  setTimeout(function timeout() {
    ws.send(Date.now());
  }, 500);
});

Other examples

For a full example with a browser client communicating with a ws server, see the examples folder.

Otherwise, see the test cases.

Error handling best practices

// If the WebSocket is closed before the following send is attempted
ws.send('something');

// Errors (both immediate and async write errors) can be detected in an optional
// callback. The callback is also the only way of being notified that data has
// actually been sent.
ws.send('something', function ack(error) {
  // If error is not defined, the send has been completed, otherwise the error
  // object will indicate what failed.
});

// Immediate errors can also be handled with `try...catch`, but **note** that
// since sends are inherently asynchronous, socket write failures will *not* be
// captured when this technique is used.
try { ws.send('something'); }
catch (e) { /* handle error */ }

FAQ

How to get the IP address of the client?

The remote IP address can be obtained from the raw socket.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws, req) {
  const ip = req.connection.remoteAddress;
});

When the server runs behind a proxy like NGINX, the de-facto standard is to use the X-Forwarded-For header.

wss.on('connection', function connection(ws, req) {
  const ip = req.headers['x-forwarded-for'];
});

How to detect and close broken connections?

Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord).

In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

function heartbeat() {
  this.isAlive = true;
}

wss.on('connection', function connection(ws) {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
});

const interval = setInterval(function ping() {
  wss.clients.forEach(function each(ws) {
    if (ws.isAlive === false) return ws.terminate();

    ws.isAlive = false;
    ws.ping('', false, true);
  });
}, 30000);

Pong messages are automatically sent in response to ping messages as required by the spec.

How to connect via a proxy?

Changelog

We're using the GitHub releases for changelog entries.

相關推薦

node.js ws模組 方法屬性websocket

WebSocket compression ws supports the permessage-deflate extension which enables the client and server to negotiate a compression algorit

Node.js FS模組方法速查

1. File System 所有檔案操作提供同步和非同步的兩種方式,本筆記只記錄非同步的API 非同步方式其最後一個引數是回撥函式。回撥函式的第一個引數往往是錯誤物件,如果沒有發生引數,那麼第一個引數可能是null或者undefinded。 同步函式可以使用try

Node.js 博客實例添加文件上傳功能

文件 ace direct 上傳文件 file form parser rec mark 原教程 https://github.com/nswbmw/N-blog/wiki/_pages的第三章 上傳文件眼下有三種方法: 使用 Express 自帶的文件上傳功能,不涉

Node.js安裝及環境配置windows

glob node mod script es2017 lob target 技術分享 系統 1.Node.js簡介  簡單的說 Node.js 就是運行在服務端的 JavaScript。Node.js 是一個基於 Chrome V8 引擎的 JavaScript 運行環境

node.js從入門到放棄

簡單的 all == ons true nts 數值 定時 註冊 上章講了學習node,應該去學習什麽,對這些框架去進行學習現在咋們聊聊如何用原生來進行操作 主要來講一下events-事件觸發器 先來講一個簡單的實例 EventEmitter的實例,綁定一個監聽器。用

node.js從入門到放棄

主鍵 data timestamp insert 代碼 了解 javascrip ice where 以下內容全是我個人理解寫出,如有不對,請立刻練習本人進行更改。以免被剛入門的被我帶入坑裏。 —node是什麽?我想大家應該都知道。 node是前端未來幹掉後

node.js零基礎學習筆記

註釋:寫完了今天的筆記,今天主要學習了,不同js檔案,如何獲取其他js檔案的方法,一個js方法的匯出另外js檔案對方法的接收(語言敘述可能不準確,就是想說我有一個蘋果你想吃我也願意給你吃,怎麼搞?我要先把蘋果拿出來的過程,和你伸手的過程,我就是一個比喻~可能不太準確,但是我是這麼理解的),以上是第一

node.js零基礎學習筆記

開始:一個前端小白接觸node.js,簡單的筆記,筆記的記錄邏輯或許不是太清晰,但是能看懂,或許對node.js的學習不精,也可能有錯誤理解的,第一次接觸,僅供和我一樣零基礎學習node.js的人,會繼續補充新增,謝謝大家~麼麼噠 NodeJS 一、簡介    wha

設計模式-模組方法模式TemplateMethod

模組方法模式是行為模式之一,它把具有特定步驟演算法中的某些必要的處理委讓給抽象方法,通過子類繼承對抽象方法的不同實現改變整個演算法的行為。 UML圖: 具體程式碼: /** * 抽象-模組方法模式核心 */ public abstract class AbstractPage {

Node.js從入門到實戰React一頁紙總結很大的一頁紙

一、React React是一個JavaScript庫,是由FaceBook和Instagram開發的,主要用於使用者建立圖形化介面。 由於 React 的設計思想極其獨特,屬於革命性創新,效能出眾,程式碼邏輯卻非常簡單。所以,越來越多的人開始關注和使用,認為它可能是

Node.js從入門到實戰Solr查詢規則總結

一、Solr Solr是一個獨立的企業級搜尋應用伺服器,它對外提供類似於Web-service的API介面。使用者可以通過http請求,向搜尋引擎伺服器提交一定格式的XML檔案,生成索引;也可以通過Http Get操作提出查詢請求,並得到XML格式的返回結果。 本文不涉及

Node.js從入門到實戰Solr的層級

參考:Node.js從入門到實戰(七)Solr查詢規則總結 一、Solr的層級 Solr作為關鍵的搜尋元件,在整個系統中的架構如下圖所示: Solr的索引服務是為了提高搜尋的效率,一般而言Solr需要配合Nosql DB使用,作為與NoSQL DB相互獨立的補充,在能夠

Node.js從入門到實戰ECMAScript6一頁紙總結很大的一頁紙

一、ES5/ES6和babel ECMAScript5,即ES5,是ECMAScript的第五次修訂,於2009年完成標準化,現在的瀏覽器已經相當於完全實現了這個標準。 ECMAScript6,即ES6,也稱ES2015,是ECMAScript的第六次修訂,於2015

Node.js從入門到實戰Node.js / JavaScript / ECMAScript的關係

一、Node.js Node.js 是一個基於 Chrome V8 引擎的 JavaScript 執行環境。 Node.js 使用了一個事件驅動、非阻塞式 I/O 的模型,使其輕量又高效。 Node.js 的包管理器 npm,是全球最大的開源庫生態系統。 V8引擎本身使用

Node.js從入門到實戰Intellj Idea 2017下的第一個Node.js工程

參考: 一、Intellj Idea下的初始工程 使用Idea建立的Node.js Express工程建立成功後執行, 二、程式碼分析 第一個工程命名為PageIron,該專案的主要程式碼位於PageIron/bin/www檔案中: Node.js 應用的組成部分:

Node.js從入門到實戰Npm使用介紹

一、NPM NPM是隨同NodeJS一起安裝的包管理工具,能解決NodeJS程式碼部署上的很多問題,常見的使用場景有以下幾種: 允許使用者從NPM伺服器下載別人編寫的第三方包到本地使用。允許使用者從NPM伺服器下載並安裝別人編寫的命令列程式到本地使用。允許使用者將自己編寫

Node.js從入門到實戰Node.js基本用法

參考: 一、Node.js中的模組 Node.js使用require引入依賴的模組,因此模組是Node.js中的重要組成部分,這篇部落格主要羅列一下常用的Node.js模組,並且在後期會新增在工作中用到的模組參考備用。 二、Node.js EventEmitter Node

Node.js Koa框架入門】Koa 框架介紹以及環境搭建、簡單使用

一、框架介紹 Koa -- 基於 Node.js 平臺的下一代 web 開發框架 koa是由 Express 原班人馬打造的,致力於成為一個更小、更富有表現力、更健壯的 Web 框架。 使用 koa 編寫 web 應用,可以免除重複繁瑣的回撥函式巢狀, 並極大地提升錯誤

cocos creator WebSocketnode.js ws通訊

1)服務端 var ws = require("ws"); var server = new ws.Server({ port: 6080 }); server.on("connection", function (session) { session.on("close

JS常用屬性方法大全

1.輸出語句:document.write("");2.JS中的註釋為://3.傳統的HTML文件順序是:document->html->(head,body)4.一個瀏覽器視窗中的DOM順序是:window->(navigator,screen,histo