NodeMCU文档中文翻译 8 Websocket模块

【转载请注明出处:http://blog.csdn.net/leytton/article/details/76217923


一、译文


Websocket客户端模块实现了 RFC6455 (版本 13)协议规范并且提供了简单的接口来收发消息.

本模块支持分片消息, 如果服务器无法响应会自动回复ping请求和定时ping.

SSL/TLS 支持

注意 net 模块 的约束条件.

websocket.createClient() 创建websocket客户端.
websocket.client:close() 关闭websocket 连接.
websocket.client:config(params) 配置websocket客户端实例.
websocket.client:connect() 与给定URL之间创建websocket连接.
websocket.client:on() 注册回调函数来处理websocket事件 (每个客户端同种事件类型只能创建一个回调函数).
websocket.client:send() 通过websocket连接发送消息.

websocket.createClient()

创建一个websocket客户端. 这个客户端可以保存到实例变量中并通过函数来处理事件.

当连接关闭, 同样的客户端是可以再次使用的 - 回调函数保持不变 - 你可以再次连接任何服务端.

在释放客户端实例前, 确保使用 ws:close().函数来关闭连接.

语法

websocket.createClient()

参数

返回值

websocketclient

示例代码
local ws = websocket.createClient()
-- ...
ws:close()
ws = nil

websocket.client:close()

关闭websocket 连接. 客户端发送一个关闭数据帧给服务器,尝试优雅地关闭连接. 如果服务器不应答, 超时后连接会关闭.

即使是websocket并未连接,这个函数也可以调用.

在客户端实例释放前必须调用此函数.

语法

websocket:close()

参数

返回值

nil

示例代码
ws = websocket.createClient()
ws:close()
ws:close() -- 不会发生任何事情

ws = nil -- 完全释放客户端实例,lua虚拟机会回收内存

websocket.client:config(params)

配置websocket客户端实例.

语法

websocket:config(params)

参数
  • params table 数据类型. 支持以下关键字:
  • headers table 数据类型,会附加到每次请求的头部
返回值

nil

示例代码
ws = websocket.createClient()
ws:config({headers={['User-Agent']='NodeMCU'}})

websocket.client:connect()

与给定URL之间创建websocket连接.

语法

websocket:connect(url)

参数
  • url websocket服务端URL.
返回值

nil

示例代码
ws = websocket.createClient()
ws:connect('ws://echo.websocket.org')

如果失败, 错误将会传递到回调函数 websocket:on("close", handler).

websocket.client:on()

注册回调函数来处理websocket事件 (每个客户端同种事件类型只能创建一个回调函数).

语法

websocket:on(eventName, function(ws, ...))

参数
  • eventName 注册回调函数事件名称. 这些事件可以是:connectionreceive 和 close.
  • function(ws, ...) 回调函数. 函数第一个参数一般为websocket客户端实例. 其他参数取决于事件类型. 查看示例代码获取更多信息. 如果为 nil, 则是取消之前该事件注册的回调函数.
返回值

nil

示例代码
local ws = websocket.createClient()
ws:on("connection", function(ws)
  print('got ws connection')
end)
ws:on("receive", function(_, msg, opcode)
  print('got message:', msg, opcode) -- opcode 为 1 则是文本消息, 为 2 则是二进制消息
end)
ws:on("close", function(_, status)
  print('connection closed', status)
  ws = nil -- 需要lua释放回收websocket客户端实例
end)

ws:connect('ws://echo.websocket.org')

注意如果产生了错误,close事件回调函数将会出发.

close事件状态码,如果不为0则表示错误, 详细描述如下表所示.

状态码 解释
0 用户关闭或者连接正常关闭
-1 URL格式错误
-2 主机名太长 (>256 字符)
-3 无效端口号 (必须 >0 且 <= 65535)
-4 主机名格式错误
-5 DNS找不到主机名
-6 服务器响应终止
-7 服务器发送无效HTTP响应(例如. 服务器发送错误的key值)
-8 to -14 内存不足无法接收消息
-15 服务器没有遵循FIN协议
-16 内存不足无法发送消息
-17 服务器不切换协议
-18 连接超时
-19 服务器不响应校验通信
-99 to -999 额,发生了一些不好的事

websocket.client:send()

通过websocket连接发送消息.

语法

websocket:send(message, opcode)

参数
  • message 要发送的数据.
  • opcode 可选设置操作码 (默认为: 1, 文本消息)
返回值

nil 如果websocket未连接则会返回错误

示例代码
ws = websocket.createClient()
ws:on("connection", function()
  ws:send('hello!')
end)
ws:connect('ws://echo.websocket.org')


二、原文

摘自https://nodemcu.readthedocs.io/en/master/en/modules/websocket/

Websocket Module

Since Origin / Contributor Maintainer Source
2016-08-02 Luís Fonseca Luís Fonseca websocket.c

A websocket client module that implements RFC6455 (version 13) and provides a simple interface to send and receive messages.

The implementation supports fragmented messages, automatically respondes to ping requests and periodically pings if the server isn't communicating.

SSL/TLS support

Take note of constraints documented in the net module.

websocket.createClient() Creates a new websocket client.
websocket.client:close() Closes a websocket connection.
websocket.client:config(params) Configures websocket client instance.
websocket.client:connect() Attempts to estabilish a websocket connection to the given URL.
websocket.client:on() Registers the callback function to handle websockets events (there can be only one handler function registered per event type).
websocket.client:send() Sends a message through the websocket connection.

websocket.createClient()

Creates a new websocket client. This client should be stored in a variable and will provide all the functions to handle a connection.

When the connection becomes closed, the same client can still be reused - the callback functions are kept - and you can connect again to any server.

Before disposing the client, make sure to call ws:close().

Syntax

websocket.createClient()

Parameters

none

Returns

websocketclient

Example
local ws = websocket.createClient()
-- ...
ws:close()
ws = nil

websocket.client:close()

Closes a websocket connection. The client issues a close frame and attemtps to gracefully close the websocket. If server doesn't reply, the connection is terminated after a small timeout.

This function can be called even if the websocket isn't connected.

This function must always be called before disposing the reference to the websocket client.

Syntax

websocket:close()

Parameters

none

Returns

nil

Example
ws = websocket.createClient()
ws:close()
ws:close() -- nothing will happen

ws = nil -- fully dispose the client as lua will now gc it

websocket.client:config(params)

Configures websocket client instance.

Syntax

websocket:config(params)

Parameters
  • params table with configuration parameters. Following keys are recognized:
  • headers table of extra request headers affecting every request
Returns

nil

Example
ws = websocket.createClient()
ws:config({headers={['User-Agent']='NodeMCU'}})

websocket.client:connect()

Attempts to estabilish a websocket connection to the given URL.

Syntax

websocket:connect(url)

Parameters
  • url the URL for the websocket.
Returns

nil

Example
ws = websocket.createClient()
ws:connect('ws://echo.websocket.org')

If it fails, an error will be delivered via websocket:on("close", handler).

websocket.client:on()

Registers the callback function to handle websockets events (there can be only one handler function registered per event type).

Syntax

websocket:on(eventName, function(ws, ...))

Parameters
  • eventName the type of websocket event to register the callback function. Those events are:connectionreceive and close.
  • function(ws, ...) callback function. The function first parameter is always the websocketclient. Other arguments are required depending on the event type. See example for more details. If nil, any previously configured callback is unregistered.
Returns

nil

Example
local ws = websocket.createClient()
ws:on("connection", function(ws)
  print('got ws connection')
end)
ws:on("receive", function(_, msg, opcode)
  print('got message:', msg, opcode) -- opcode is 1 for text message, 2 for binary
end)
ws:on("close", function(_, status)
  print('connection closed', status)
  ws = nil -- required to lua gc the websocket client
end)

ws:connect('ws://echo.websocket.org')

Note that the close callback is also triggered if any error occurs.

The status code for the close, if not 0 then it represents an error, as described in the following table.

Status Code Explanation
0 User requested close or the connection was terminated gracefully
-1 Failed to extract protocol from URL
-2 Hostname is too large (>256 chars)
-3 Invalid port number (must be >0 and <= 65535)
-4 Failed to extract hostname
-5 DNS failed to lookup hostname
-6 Server requested termination
-7 Server sent invalid handshake HTTP response (i.e. server sent a bad key)
-8 to -14 Failed to allocate memory to receive message
-15 Server not following FIN bit protocol correctly
-16 Failed to allocate memory to send message
-17 Server is not switching protocols
-18 Connect timeout
-19 Server is not responding to health checks nor communicating
-99 to -999 Well, something bad has happenned

websocket.client:send()

Sends a message through the websocket connection.

Syntax

websocket:send(message, opcode)

Parameters
  • message the data to send.
  • opcode optionally set the opcode (default: 1, text message)
Returns

nil or an error if socket is not connected

Example
ws = websocket.createClient()
ws:on("connection", function()
  ws:send('hello!')
end)
ws:connect('ws://echo.websocket.org')



转载于:https://www.cnblogs.com/leytton/p/8253257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值