or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-websocket

Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/websocket@1.0.x

To install, run

npx @tessl/cli install tessl/npm-websocket@1.0.0

0

# WebSocket

1

2

WebSocket is a comprehensive Node.js library that implements the WebSocket protocol as specified in RFC 6455. It provides both client and server functionality with support for multiple WebSocket protocol versions (8 and 13), featuring extensive configuration options, automatic message fragmentation, keepalive functionality, and W3C-compliant APIs.

3

4

## Package Information

5

6

- **Package Name**: websocket

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install websocket`

10

11

## Core Imports

12

13

```javascript

14

const WebSocket = require('websocket');

15

16

// Access individual components

17

const server = WebSocket.server;

18

const client = WebSocket.client;

19

const router = WebSocket.router;

20

const frame = WebSocket.frame;

21

const connection = WebSocket.connection;

22

const request = WebSocket.request;

23

const w3cwebsocket = WebSocket.w3cwebsocket;

24

const version = WebSocket.version;

25

```

26

27

For browser usage:

28

29

```javascript

30

const { w3cwebsocket: W3CWebSocket, version } = require('websocket/lib/browser');

31

32

// Use native WebSocket if available, fallback to library implementation

33

const WebSocketClass = W3CWebSocket || WebSocket;

34

```

35

36

## Basic Usage

37

38

### Quick Server Setup

39

40

```javascript

41

const WebSocket = require('websocket');

42

const http = require('http');

43

44

// Create HTTP server

45

const server = http.createServer();

46

server.listen(8080);

47

48

// Create WebSocket server

49

const wsServer = new WebSocket.server({

50

httpServer: server,

51

autoAcceptConnections: false

52

});

53

54

wsServer.on('request', function(request) {

55

const connection = request.accept(null, request.origin);

56

57

connection.on('message', function(message) {

58

if (message.type === 'utf8') {

59

console.log('Received: ' + message.utf8Data);

60

connection.sendUTF('Echo: ' + message.utf8Data);

61

}

62

});

63

});

64

```

65

66

### Quick Client Setup

67

68

```javascript

69

const WebSocket = require('websocket');

70

71

const client = new WebSocket.client();

72

73

client.on('connect', function(connection) {

74

connection.sendUTF('Hello Server!');

75

76

connection.on('message', function(message) {

77

console.log('Received: ' + message.utf8Data);

78

});

79

});

80

81

client.connect('ws://localhost:8080/');

82

```

83

84

## Architecture

85

86

WebSocket is built around several key components:

87

88

- **Server Infrastructure**: `WebSocketServer` handles HTTP upgrade requests and manages connections

89

- **Client Infrastructure**: `WebSocketClient` creates outbound connections with full configuration control

90

- **Connection Management**: `WebSocketConnection` provides bidirectional communication with event-driven message handling

91

- **Request Processing**: `WebSocketRequest` manages the handshake process with accept/reject capabilities

92

- **Routing System**: `WebSocketRouter` enables path and protocol-based request routing

93

- **W3C Compliance**: `W3CWebSocket` provides standard WebSocket API compatibility

94

- **Frame Processing**: `WebSocketFrame` handles low-level protocol frame parsing and construction

95

96

## Capabilities

97

98

### Server-Side WebSocket Handling

99

100

Complete server-side WebSocket implementation with HTTP server integration, request routing, and connection management.

101

102

```javascript { .api }

103

// Main server class

104

class WebSocketServer extends EventEmitter {

105

constructor(config?: ServerConfig);

106

mount(config: ServerConfig): void;

107

unmount(): void;

108

closeAllConnections(): void;

109

broadcast(data: Buffer | string): void;

110

shutDown(): void;

111

}

112

113

// Request handling

114

class WebSocketRequest extends EventEmitter {

115

accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: Cookie[]): WebSocketConnection;

116

reject(status?: number, reason?: string, extraHeaders?: object): void;

117

}

118

119

// Routing system

120

class WebSocketRouter extends EventEmitter {

121

mount(path: string | RegExp, protocol: string, callback: (request: WebSocketRouterRequest) => void): void;

122

unmount(path: string | RegExp, protocol: string): void;

123

}

124

```

125

126

[Server-Side Operations](./server.md)

127

128

### Client-Side WebSocket Connections

129

130

Outbound WebSocket client with full protocol support and W3C-compliant API.

131

132

```javascript { .api }

133

// Native WebSocket client

134

class WebSocketClient extends EventEmitter {

135

constructor(config?: ClientConfig);

136

connect(requestUrl: string, protocols?: string | string[], origin?: string, headers?: object, extraRequestOptions?: object): void;

137

abort(): void;

138

}

139

140

// W3C-compliant WebSocket API

141

class W3CWebSocket {

142

constructor(url: string, protocols?: string | string[], origin?: string, headers?: object, requestOptions?: object, clientConfig?: object);

143

send(data: string | Buffer | ArrayBuffer): void;

144

close(code?: number, reason?: string): void;

145

readonly readyState: number;

146

readonly protocol: string;

147

}

148

```

149

150

[Client-Side Operations](./client.md)

151

152

### Bidirectional Connection Communication

153

154

Active WebSocket connection handling for both client and server sides with comprehensive message and event support.

155

156

```javascript { .api }

157

class WebSocketConnection extends EventEmitter {

158

send(data: Buffer | string, callback?: (error?: Error) => void): void;

159

sendUTF(data: string, callback?: (error?: Error) => void): void;

160

sendBytes(data: Buffer, callback?: (error?: Error) => void): void;

161

ping(data?: Buffer): void;

162

close(reasonCode?: number, description?: string): void;

163

drop(reasonCode?: number, description?: string, skipCloseFrame?: boolean): void;

164

165

readonly connected: boolean;

166

readonly state: string;

167

readonly protocol: string;

168

readonly remoteAddress: string;

169

}

170

```

171

172

[Connection Management](./connection.md)

173

174

### Low-Level Frame Processing

175

176

Direct WebSocket frame parsing and construction for advanced use cases.

177

178

```javascript { .api }

179

class WebSocketFrame {

180

constructor(maskBytes?: Buffer, frameHeader?: object, config?: object);

181

addData(buffer: Buffer): boolean;

182

toBuffer(nullMask?: boolean): Buffer;

183

184

fin: boolean;

185

opcode: number;

186

length: number;

187

binaryPayload: Buffer;

188

}

189

```

190

191

[Frame-Level Operations](./frame.md)

192

193

### Router Request Processing

194

195

Simplified request handling within router context for path and protocol-based routing.

196

197

```javascript { .api }

198

class WebSocketRouterRequest extends EventEmitter {

199

accept(origin?: string, cookies?: Cookie[]): WebSocketConnection;

200

reject(status?: number, reason?: string, extraHeaders?: object): void;

201

202

readonly webSocketRequest: WebSocketRequest;

203

readonly protocol: string;

204

readonly origin: string;

205

readonly resource: string;

206

}

207

```

208

209

[Router Request Handling](./router-request.md)

210

211

### Utilities and Version Information

212

213

Library version information, deprecation handling, and utility functions.

214

215

```javascript { .api }

216

// Version information

217

const version: string;

218

219

// Deprecation management

220

class Deprecation {

221

static disableWarnings: boolean;

222

static warn(deprecationName: string): void;

223

}

224

225

// Browser compatibility

226

interface BrowserExports {

227

w3cwebsocket: typeof W3CWebSocket | null;

228

version: string;

229

}

230

```

231

232

[Utilities and Version Information](./utilities.md)

233

234

## Types

235

236

### Configuration Types

237

238

```javascript { .api }

239

interface ServerConfig {

240

httpServer: http.Server | https.Server | http.Server[];

241

maxReceivedFrameSize?: number;

242

maxReceivedMessageSize?: number;

243

fragmentOutgoingMessages?: boolean;

244

fragmentationThreshold?: number;

245

keepalive?: boolean;

246

keepaliveInterval?: number;

247

dropConnectionOnKeepaliveTimeout?: boolean;

248

keepaliveGracePeriod?: number;

249

useNativeKeepalive?: boolean;

250

assembleFragments?: boolean;

251

autoAcceptConnections?: boolean;

252

ignoreXForwardedFor?: boolean;

253

parseCookies?: boolean;

254

parseExtensions?: boolean;

255

disableNagleAlgorithm?: boolean;

256

closeTimeout?: number;

257

}

258

259

interface ClientConfig {

260

maxReceivedFrameSize?: number;

261

maxReceivedMessageSize?: number;

262

fragmentOutgoingMessages?: boolean;

263

fragmentationThreshold?: number;

264

webSocketVersion?: number;

265

assembleFragments?: boolean;

266

disableNagleAlgorithm?: boolean;

267

closeTimeout?: number;

268

tlsOptions?: object;

269

}

270

```

271

272

### Message and Event Types

273

274

```javascript { .api }

275

interface WebSocketMessage {

276

type: 'utf8' | 'binary';

277

utf8Data?: string;

278

binaryData?: Buffer;

279

}

280

281

interface Cookie {

282

name: string;

283

value: string;

284

path?: string;

285

domain?: string;

286

expires?: Date;

287

maxage?: number;

288

secure?: boolean;

289

httponly?: boolean;

290

}

291

```

292

293

### Close Reason Constants

294

295

```javascript { .api }

296

const CLOSE_REASONS = {

297

NORMAL: 1000,

298

GOING_AWAY: 1001,

299

PROTOCOL_ERROR: 1002,

300

UNPROCESSABLE_INPUT: 1003,

301

RESERVED: 1004,

302

NOT_PROVIDED: 1005,

303

ABNORMAL: 1006,

304

INVALID_DATA: 1007,

305

POLICY_VIOLATION: 1008,

306

MESSAGE_TOO_BIG: 1009,

307

EXTENSION_REQUIRED: 1010,

308

INTERNAL_SERVER_ERROR: 1011,

309

TLS_HANDSHAKE_FAILED: 1015

310

};

311

```