Nodejs Websocket

Build Status Inline docs Dependency Status

A nodejs module for websocket server and client用于websocket服务器和客户端的nodejs模块

How to use it如何使用它

Install with npm install nodejs-websocket or put all files in a folder called "nodejs-websocket", and:使用npm install nodejs-websocket安装或将所有文件放在名为“nodejs-websocket”的文件夹中,然后:

var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("text", function (str) {
		console.log("Received "+str)
		conn.sendText(str.toUpperCase()+"!!!")
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
	})
}).listen(8001)

Se other examples inside the folder samples请参阅文件夹示例中的其他示例

ws

The main object, returned by require("nodejs-websocket").主对象,由require("nodejs-websocket")返回。

ws.createServer([options], [callback])

Returns a new Server object.返回一个新的Server对象。

The options is an optional object that will be handed to net.createServer() to create an ordinary socket. 这些options是一个可选对象,将传递给net.createServer()以创建普通套接字。If it has a property called "secure" with value true, tls.createServer() will be used instead.如果它有一个名为“secure”且值为true的属性,则将使用tls.createServer()

To support protocols, the options object may have either of these properties:要支持协议,options对象可以具有以下属性之一:

The callback is a function which is automatically added to the "connection" event.callback是自动添加"connection"事件中的函数。

ws.connect(URL, [options], [callback])

Returns a new Connection object, representing a websocket client connection返回表示websocket客户端连接的新Connection对象

URL is a string with the format "ws://localhost:8000/chat" (the port can be omitted)是格式为“ws://localhost:8000/chat”的字符串(端口可以省略)

options is an object that will be passed to net.connect() (or tls.connect() if the protocol is "wss:").是将传递给net.connect()的对象(如果协议为“wss:”,则传递给tls.connect()The properties "host" and "port" will be read from the URL.属性“host”和“port”将从URL中读取。The optional property extraHeaders will be used to add more headers to the HTTP handshake request. 可选属性extraHeaders将用于向HTTP握手请求添加更多的头。If present, it must be an object, like {'X-My-Header': 'value'}.如果存在,它必须是一个对象,如{'X-My-Header': 'value'}The optional property protocols will be used in the handshake (as "Sec-WebSocket-Protocol" header) to allow the server to choose one of those values. 可选属性protocols将用于握手(作为“Sec WebSocket Protocol”头),以允许服务器选择其中一个值。If present, it must be an array of strings.如果存在,则它必须是字符串数组。

callback will be added as "connect" listener将添加为“连接”侦听器

ws.setBinaryFragmentation(bytes)

Sets the minimum size of a pack of binary data to send in a single frame (default: 512kiB)设置要在单个帧中发送的二进制数据包的最小大小(默认值:512KB)

ws.setMaxBufferLength(bytes)

Set the maximum size the internal Buffer can grow (default: 2MiB). 设置内部缓冲区可以增长的最大大小(默认值:2MiB)。If at any time it stays bigger than this, the connection will be closed with code 1009. 如果在任何时候它保持大于此值,则连接将以代码1009关闭。This is a security measure, to avoid memory attacks这是一种安全措施,以避免内存攻击

Server

The class that represents a websocket server, much like a HTTP server表示websocket服务器的类,非常类似于HTTP服务器

server.listen(port, [host], [callback])

Starts accepting connections on a given port and host.开始接受给定porthost上的连接。

If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).如果省略host,服务器将接受指向任何IPv4地址(INADDR\U any)的连接。

A port value of zero will assign a random port.port值为零将分配一个随机端口。

callback will be added as an listener for the 'listening' event.将添加为'listening'事件的侦听器。

server.close([callback])

Stops 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.“close”事件发生后,将调用可选回调。

server.socket

The underlying socket, returned by net.createServer or tls.createServernet.createServertls.createServer返回的基础套接字

server.connections

An Array with all connected clients. 包含所有已连接客户端的阵列。It's useful for broadcasting a message:它对于广播信息很有用:

function broadcast(server, msg) {
	server.connections.forEach(function (conn) {
		conn.sendText(msg)
	})
}

Event: 'listening()'

Emitted when the server has been bound after calling server.listen调用server.listen后绑定服务器时发出

Event: 'close()'

Emitted when the server closes. 服务器关闭时发出。Note that if connections exist, this event is not emitted until all connections are completely ended.请注意,如果存在连接,则在所有连接完全结束之前不会发出此事件。

Event: 'error(errObj)'

Emitted when an error occurs. 发生错误时发出。The 'close' event will be called directly following this event.'close'事件将在此事件后直接调用。

Event: 'connection(conn)'

Emitted when a new connection is made successfully (after the handshake have been completed). 成功建立新连接时发出(握手完成后)。conn is an instance of Connectionconn是连接的一个实例

Connection联系

The class that represents a connection, either a client-created (accepted by a nodejs ws server) or client connection. 表示连接的类,可以是创建的客户端(由nodejs ws服务器接受)或客户端连接。The websocket protocol has two types of data frames: text and binary.websocket协议有两种类型的数据帧:文本和二进制。Text frames are implemented as simple send function and receive event. 文本帧实现为简单的发送函数和接收事件。Binary 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.二进制帧被实现为流:当您接收到二进制数据时,您得到一个可读流;要发送二进制数据,必须请求可写流并写入其中。The binary data will be divided into frames and be sent over the socket.二进制数据将被分成帧,并通过套接字发送。

You cannot send text data while sending binary data. 发送二进制数据时不能发送文本数据。If you try to do so, the connection will emit an "error" event如果您尝试这样做,连接将发出一个“错误”事件

connection.sendText(str, [callback])

Sends a given string to the other side. 将给定字符串发送到另一端。You can't send text data in the middle of a binary transmission.不能在二进制传输的中间发送文本数据。

callback will be added as a listener to write operation over the socket将作为侦听器添加到套接字上的写入操作

connection.beginBinary()

Asks the connection to begin transmitting binary data. 要求连接开始传输二进制数据。Returns a WritableStream.返回一个可写流。The binary transmission will end when the WritableStream finishes (like when you call .end on it)二进制传输将在可写流完成时结束(如调用.end时)

connection.sendBinary(data, [callback])

Sends a single chunk of binary data (like calling connection.beginBinary().end(data))发送单个二进制数据块(如调用connection.beginBinary().end(data)

callback will be added as a listener to write operation over the socket将作为侦听器添加到套接字上的写入操作

connection.send(data, [callback])

Sends 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.如果数据是字符串,这只是sendText()的别名;如果数据是缓冲区,这只是sendBinary()的别名。

callback will be added as a listener to write operation over the socket将作为侦听器添加到套接字上的写入操作

connection.sendPing([data=''])

Sends a ping with optional payload发送带有可选负载的ping

connection.close([code, [reason]])

Starts the closing handshake (sends a close frame)开始结束握手(发送结束帧)

connection.socket

The underlying net or tls socket底层网络或tls套接字

connection.server

If the connection was accepted by a nodejs server, a reference to it will be saved here. 如果nodejs服务器接受了该连接,将在此处保存对该连接的引用。null otherwise否则为null

connection.readyState

One of these constants, representing the current state of the connection. 这些常量之一,表示连接的当前状态。Only an open connection can be used to send/receive data.只有打开的连接才能用于发送/接收数据。

connection.outStream

Stores the OutStream object returned by connection.beginBinary(). 存储connection.beginBinary()返回的扩展流对象。null if there is no current binary data beeing sent.如果当前未发送二进制数据,则为null

connection.path

For a connection accepted by a server, it is a string representing the path to which the connection was made (example: "/chat"). 对于服务器接受的连接,它是表示连接路径的字符串(例如:“/chat”)。null otherwise否则为null

connection.headers

Read only map of header names and values. Header names are lower-cased标题名称和值的只读映射。标题名称小写

connection.protocols

Array of protocols requested by the client. 客户端请求的协议数组。If no protocols were requested, it will be an empty array.如果未请求任何协议,则它将是一个空数组。

Additional resources on websocket subprotocols:有关websocket子目录的其他资源:

connection.protocol

The protocol agreed for this connection, if any. 该协议同意用于此连接(如果有)。It will be an element of connection.protocols.它将是connection.protocols的一个元素。

Event: 'close(code, reason)'

Emitted when the connection is closed by any side当任何一侧关闭连接时发出

Event: 'error(err)'

Emitted in case of error (like trying to send text data while still sending binary data).在发生错误时发出(如在发送二进制数据的同时尝试发送文本数据)。In case of an invalid handshake response will also be emited.如果握手无效,也会发出响应。

Event: 'text(str)'

Emitted when a text is received. 接收到文本时发出。str is a string是一个字符串。

Event: 'binary(inStream)'

Emitted when the beginning of binary data is received. 当接收到二进制数据的开头时发出。inStream is a ReadableStream:

var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("binary", function (inStream) {
		// Empty buffer for collecting binary data
		var data = Buffer.alloc(0)
		// Read chunks of binary data and add to the buffer
		inStream.on("readable", function () {
		    var newData = inStream.read()
		    if (newData)
		        data = Buffer.concat([data, newData], data.length+newData.length)
		})
		inStream.on("end", function () {
			console.log("Received " + data.length + " bytes of binary data")
		    process_my_data(data)
		})
	})
	conn.on("close", function (code, reason) {
		console.log("Connection closed")
	})
}).listen(8001)

Event: 'connect()'

Emitted when the connection is fully established (after the handshake)完全建立连接时发出(握手后)

Event: 'pong(data)'

Emitted when a pong is received, usually after a ping was sent. 收到pong时发出,pong通常在发出ping后发出。data is the pong payload, as a stringdata是pong有效负载,作为字符串