# ws: a Node.js WebSocket library
[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws)
[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws)
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.
Passes the quite extensive Autobahn test suite: [server][server-report],
[client][client-report].
**Note**: This module does not work in the browser. The client in the docs is a
reference to a back end with the role of a client in the WebSocket
communication. Browser clients must use the native
[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
object. To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like
[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws).
## Table of Contents
- [Protocol support](#protocol-support)
- [Installing](#installing)
- [Opt-in for performance](#opt-in-for-performance)
- [Legacy opt-in for performance](#legacy-opt-in-for-performance)
- [API docs](#api-docs)
- [WebSocket compression](#websocket-compression)
- [Usage examples](#usage-examples)
- [Sending and receiving text data](#sending-and-receiving-text-data)
- [Sending binary data](#sending-binary-data)
- [Simple server](#simple-server)
- [External HTTP/S server](#external-https-server)
- [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
- [Client authentication](#client-authentication)
- [Server broadcast](#server-broadcast)
- [Round-trip time](#round-trip-time)
- [Use the Node.js streams API](#use-the-nodejs-streams-api)
- [Other examples](#other-examples)
- [FAQ](#faq)
- [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
- [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
- [How to connect via a proxy?](#how-to-connect-via-a-proxy)
- [Changelog](#changelog)
- [License](#license)
## Protocol support
- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
- **HyBi drafts 13-17** (Current default, alternatively option
`protocolVersion: 13`)
## Installing
```
npm install ws
```
### Opt-in for performance
[bufferutil][] is an optional module that can be installed alongside the ws
module:
```
npm install --save-optional bufferutil
```
This is a binary addon that improves the performance of certain operations such
as masking and unmasking the data payload of the WebSocket frames. Prebuilt
binaries are available for the most popular platforms, so you don't necessarily
need to have a C++ compiler installed on your machine.
To force ws to not use bufferutil, use the
[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This
can be useful to enhance security in systems where a user can put a package in
the package search path of an application of another user, due to how the
Node.js resolver algorithm works.
#### Legacy opt-in for performance
If you are running on an old version of Node.js (prior to v18.14.0), ws also
supports the [utf-8-validate][] module:
```
npm install --save-optional utf-8-validate
```
This contains a binary polyfill for [`buffer.isUtf8()`][].
To force ws to not use utf-8-validate, use the
[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable.
## API docs
See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and
utility functions.
## WebSocket compression
ws supports the [permessage-deflate extension][permessage-deflate] 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.
Note that Node.js has a variety of issues with high-performance compression,
where increased concurrency, especially on Linux, can lead to [catastrophic
memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
permessage-deflate in production, it is worthwhile to set up a test
representative of your workload and ensure Node.js/zlib will handle it with
acceptable performance and memory usage.
Tuning of permessage-deflate can be done via the options defined below. You can
also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly
into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
See [the docs][ws-server-options] for more options.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({
port: 8080,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
}
});
```
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`.
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false
});
```
## Usage examples
### Sending and receiving text data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});
```
### Sending binary data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
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);
});
```
### Simple server
```js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
```
### External HTTP/S server
```js
import { createServer } from 'https';
import { readFileSync } from 'fs';
import { WebSocketServer } from 'ws';
const server = createServer({
cert: readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem')
});
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
server.listen(8080);
```
### Multiple servers sharing a single HTTP/S server
```js
import { createServer } from 'http';
import { parse } from 'url';
import { WebSocketServer } from 'ws';
const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });
wss1.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
wss2.on('connection
没有合适的资源?快使用搜索试试~ 我知道了~
手机上的多个设备位置共享
共688个文件
meta:361个
cs:169个
asset:44个
需积分: 5 0 下载量 3 浏览量
2024-05-01
01:10:57
上传
评论
收藏 14.56MB RAR 举报
温馨提示
手机上的多个设备位置共享
资源推荐
资源详情
资源评论
收起资源包目录
手机上的多个设备位置共享 (688个子文件)
HuaweiARSDK.aar 382KB
HUAWEI_AR_Engine_UnityPlugin.aar 214KB
AndroidPermissionManager.aar 18KB
HUAWEI AR Engine Plugin_Optional.aar 15KB
HUAWEI AR Engine Plugin_Required.aar 15KB
emptymodulenoresizeable.aar 15KB
UnityWebSocket.Editor.asmdef 365B
UnityWebSocket.Runtime.asmdef 306B
HWAugImgDb.asset 3.18MB
NewDatabase.asset 508KB
ProjectSettings.asset 21KB
OpenXR Package Settings.asset 13KB
QualitySettings.asset 6KB
InputManager.asset 6KB
XRGeneralSettings.asset 2KB
GraphicsSettings.asset 2KB
Physics2DSettings.asset 2KB
NavMeshAreas.asset 1KB
MemorySettings.asset 1KB
DynamicsManager.asset 1KB
EditorUserSettings.asset 1KB
EditorBuildSettings.asset 1023B
PackageManagerSettings.asset 1002B
EditorSettings.asset 970B
UnityConnectSettings.asset 901B
ReferenceImageLibrary.asset 793B
AugImageWorldConfig 1.asset 682B
AugImageWorldConfig.asset 589B
Magic Leap Settings.asset 569B
WorldARConfig.asset 562B
AugImageARConfig.asset 549B
BodyARConfig.asset 543B
SceneMeshARConfig.asset 543B
WorldBodyARConfig.asset 527B
HandARConfig.asset 505B
3DHandConfig.asset 505B
FaceARConfig.asset 462B
AR Core Settings.asset 451B
AR Kit Settings.asset 443B
AudioManager.asset 416B
AR Core Loader Settings.asset 412B
Open XR Loader.asset 403B
AR Core Loader.asset 403B
AR Kit Loader.asset 402B
TagManager.asset 378B
VFXManager.asset 308B
TimeManager.asset 202B
VersionControlSettings.asset 188B
XRSettings.asset 158B
PresetManager.asset 146B
ClusterInputManager.asset 114B
XRPackageSettings.asset 73B
augmented_image_cli_linux 5.03MB
augmented_image_cli_osx 9.29MB
start.bat 58B
boot.config 0B
ARFrame.cs 23KB
ARBody.cs 18KB
ARSessionAdapter.cs 16KB
ARFrameAdapter.cs 16KB
ARSession.cs 16KB
ARHand.cs 13KB
ARCameraMetadataValue.cs 13KB
ARAugmentedImageDatabaseInspector.cs 12KB
ARPlane.cs 12KB
ARConfigBaseAdapter.cs 11KB
WebSocket.cs 11KB
ARHandAdapter.cs 11KB
BodySkeletonVisualizer.cs 10KB
ARBodyAdapter.cs 9KB
ARCameraMetadataTag.cs 9KB
SettingsWindow.cs 9KB
ARAugmentedImageDatabase.cs 8KB
SessionComponent.cs 8KB
HandVisualizer.cs 8KB
ARFace.cs 7KB
ARFaceGeometryAdapter.cs 7KB
UnityWebSocketDemo.cs 7KB
AsyncTask.cs 7KB
testwebsocket.cs 6KB
AndroidPermissionsRequest.cs 6KB
ARPlaneAdapter.cs 6KB
AREnginesApk.cs 6KB
ARTrackableManager.cs 6KB
ARCameraMetadataAdapter.cs 6KB
ARCameraImageBytes.cs 6KB
ARHitResultAdapter.cs 6KB
ARFaceGeometry.cs 5KB
WebSocketManager.cs 5KB
ARTrackbale.cs 5KB
ARSessionManager.cs 5KB
ARTrackbaleAdapter.cs 5KB
ARAugmentedImageDatabaseContextMenu.cs 5KB
IWebSocket.cs 5KB
WebSocket.cs 5KB
AugmentedImageExampleController.cs 5KB
ARConfigBase.cs 5KB
ARAugmentedImageDatabaseAdapter.cs 5KB
ARPointCloudAdapter.cs 5KB
ARAnchor.cs 5KB
共 688 条
- 1
- 2
- 3
- 4
- 5
- 6
- 7
资源评论
keefor
- 粉丝: 526
- 资源: 15
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功