[译] socket.io官方文档·下篇

[译] socket.io官方文档·下篇

全篇共 7511 字。按500字/分钟阅读,预计用时 15.0 分钟。总访问 603 次,日访问 2 次。

socket.io基于WebSocket协议封装,兼容不支持ws的浏览器采用ajax轮询,socket.io为开发者提供服务端和客户端两套库,无需了解全部ws底层原理,好入门,上手快。学会socket.io后可搭建类似QQ和微信这种即时通信工具的Web版,既可以一对一对话也可开房间组队创建聊天群组,我尝试过传输的媒体类型有文本、图像两种,数据都可由1和0表示,所以理论上可传输任何媒体形式。

客户端API

IO

如果你使用的是标准化的JS库,则暴露为io这一命名空间;如果你是用Node 编译,则使用

require('socket.io-client')

引入socket.io的JS库

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io('http://localhost');
</script>

导入socket.io模块

const io = require('socket.io-client');
// or with import syntax
import io from 'socket.io-client';

io.protocol

(数值型)

表示协议版本号。

io(url[, options])

url (字符串)默认的指向 widnow.location

option (Object)

forceNew (布尔型)是否重用当前已存在的链接。

Return Socket

使用给定的URL创建一个新的 Manager ,并且尝试重用一个已存在的 Manager 等待随后调用,除非 multiplex 的选项为 false ,作用同 force new connection:true 或者 forceNew: true。

一个新的socket实例将返回命名空间指定的socket,该命名空间由URL指定,默认的为 / 。举个栗子,如果 url 为http://localhost/users, 则将会对 http://localhost 进行传输连接,并且Socket.IO连接将会对/users建立连接。

你也也可以提供查询参数,直接将查询参数添加到 url 上即可:

http://localhost/users?token=abc

详情查看new Manager(url[, options])

初始化示例

使用多路复用

默认的,当连接道不同的命名空间后一个单一的链接将会被使用。

const socket = io();
const adminSocket = io('/admin');
// a single connection will be established

注意:重用相同的命名空间将会创建两个连接:

const socket = io();
const socket2 = io();
// will also create two distinct connections

自定义path

const socket = io('http://localhost', {
  path: '/myownpath'
});

// server-side
const io = require('socket.io')({
  path: '/myownpath'
});

这里,socket连接到 admin 命名空间,使用自定义的路径 mypath。

请求地址看起来像这样:

localhost/mypath/?EIO=3&transport=polling&sid=<id>

命名空间将会作为数据的一部分被发送。

携带查询参数

const socket = io('http://localhost?token=abc');
// server-side
const io = require('socket.io')();
// middleware
io.use((socket, next) => {
  let token = socket.handshake.query.token;
  if (isValid(token)) {
    return next();
  }
  return next(new Error('authentication error'));
});
// then
io.on('connection', (socket) => {
  let token = socket.handshake.query.token;
  // ...
});

携带查询选项

const socket = io({
  query: {
    token: 'cde'
  }
});

查询内容可以在重新连接时更新:

socket.on('reconnect_attempt', () => {
  socket.io.opts.query = {
    token: 'fgh'
  }
});

携带额外的请求头 extraHeaders

仅当建立的是轮询连接时才起作用(默认为polling轮询),当使用 websocket 建立传输时,自定义的请求头将不会被添加,因为WebSockets握手信号不信任自定义的请求头

const socket = io({
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});
// 服务器端
const io = require('socket.io')();
// 中间件
io.use((socket, next) => {
  let clientId = socket.handshake.headers['x-clientid'];
  if (isValid(clientId)) {
    return next();
  }
  return next(new Error('authentication error'));
});

仅当通过 websocket 传输时

默认的,长轮询连接会被首次创建,随后升级到更好的传输方式(比如WebSocket)。

如果你喜欢挑战性,这一部分可以被跳过。

const socket = io({
  transports: ['websocket']
});
// on reconnection, reset the transports option, as the Websocket
// connection may have failed (caused by proxy, firewall, browser, ...)
socket.on('reconnect_attempt', () => {
  socket.io.opts.transports = ['polling', 'websocket'];
});

携带自定义的解析器

const parser = require('socket.io-msgpack-parser'); // or require('socket.io-json-parser')
const socket = io({
  parser: parser
});

// the server-side must have the same parser, to be able to communicate
const io = require('socket.io')({
  parser: parser
});

Manager

new Manager(url[, options])

url (字符串)

options (对象)

path (字符串) 命名路径,用来捕获服务器端的服务,默认为socket.io

reconnection (布尔型)是否自动重新建立连接,默认为 true

reconnectionAttempts (Number) 尝试重连的次数,默认为无限次

reconnectionDelay (数值型) 重寻创建连接的延迟时长,默认为1000毫秒,受 randomizationFactor 正负加减的影响。比如默认的初始化延迟将在500至1500毫秒之间。

reconnectionDelayMax (数值型)最大的重连等待时间,默认为5000毫秒。每一次尝试都会以两倍的增量增加重连的时间。

randomizationFactor (数值型)默认为0.5,最小为0,最大为1.

timeout (数值型) connect_error 和 connect_timeout 事件触发前的延迟时间,默认为20000毫秒。

autoConnect (布尔型) 如果设置为 fasle ,你不得不手动调用 manage.open 函数。

query (对象):当连接到一个命名空间,额外的查询参数将被发送(随后可以到服务器端查找 socket.handshake.query 对象)。

parser (解析器):默认的为一个Parser实例

Return Manager

这一选项同样可通过engine.io-client初始化

manager.reconnection([value])

value (布尔型)

Return Manager | Boolean

设置 reconnection 选项,或者如果没有传递参数则直接返回它。

manager.reconnectionAttempts([value])

value (数值型)

Return Manager | Number

设置reconnectionAttempts选项,或者当没有参数时直接返回。


manager.reconnectionDelay([value])

  • value (数值型)
  • Return Manager | Number

设置reconnectionDelay选项,或者当没有参数时直接返回。


manager.reconnectionDelayMax([value])

  • value (数值型)
  • Return Manager | Number

设置reconnectionDelayMax选项,或者当没有参数时直接返回。


manager.timeout([value])

  • value (数值型)
  • Return Manager | Number

设置timeout选项,或者当没有参数时直接返回。


manager.open([callback])

  • callback (Function)
  • Return Manager

如果manager使用autoConnect初始化为false,尝试运行一个新的连接。

这个回调函数参数时可选择的,并且将会在错误或者成功后被执行一次。


manager.connect([callback])

同**manager.open([callbakc])


manager.socket(nsp, options)

  • nsp (字符串)
  • options (对象)
  • Return Socket

使用给定的命名空间创建一个新的Socket连接。

Event: ‘connect_error’

  • error (对象) 错误对象

触发连接错误事件。

Event: ‘connect_timeout’

触发连接超时事件

Event: ‘reconnect’

  • attempt (数值型)尝试重新连接的次数

触发成功连接的事件

Event: ‘reconnect_attempt’

触发尝试重新连接

Event: ‘reconnecting’

  • attempt (数值型) 重新连接尝试次数

触发成功重新连接事件

Event: ‘reconnect_error’

  • error (对象)错误对象

触发当在reconnectionAttempts次数内无法重新连接的错误事件

Event: ‘ping’

当请求ping发送到服务器端时。

Event: ‘pong’

  • ms (数值型) 自ping至pong经过的毫秒数

当接受到服务器端的pong时触发。

Sokect

socket.id

  • (字符串)

标志socket session一个独一无二的符号,在客户端连接到服务器后被设置。

const socket = io(‘http://localhost’);

console.log(socket.id); // undefined

socket.on(‘connect’, () => {
console.log(socket.id); // ‘G5p5…’
});


socket.open()

* Returns Socket

手动打开socket

const socket = io({
autoConnect: false
});

// …
socket.open();


同样,也可以重新连接:

socket.on(‘disconnect’, () => {
socket.open();
});


socket.connect()

用法同**socket.open()**

socket.send([...args][, ack])

* args
* ack (Function)
* Returns Socket

发送一个**message**事件,详细查看<a target="_blank" href="https://socket.io/docs/client-api/#socket-emit-eventname-args-ack">socket.emit(eventName[, ...args][, ack]).</a>

socket.emit(eventName[, ...args][, ack])

* eventName (字符串)
* args
* ack (Function)
* Returns Socket

通过提供的name时间名称向socket标志发送事件,任何其他的参数都可被包含,所有可被序列化的数据结构都支持,包括Buffer。

socket.emit(‘hello’, ‘world’);
socket.emit(‘with-binary’, 1, ‘2’, { 3: ‘4’, 5: new Buffer(6) });


**ack**参数将用来响应服务器用来确认消息的应答。

socket.emit(‘ferret’, ‘tobi’, (data) => {
console.log(data); // data will be ‘woot’
});

// server:
// io.on(‘connection’, (socket) => {
// socket.on(‘ferret’, (name, fn) => {
// fn(‘woot’);
// });
// });


socket.on(eventName, callback)

* eventName (字符串)
* callback (Function)
* Returns Socket

注册一个新的响应服务器事件的事件处理器。

socket.on(‘news’, (data) => {
console.log(data);
});

// with multiple arguments
socket.on(‘news’, (arg1, arg2, arg3, arg4) => {
// …
});
// with callback
socket.on(‘news’, (cb) => {
cb(0);
});


这个socket实际上继承Emitter类的所有方法,比如**hashListener"",**once**,**off**(用来移除一个事件监听器)。

socket.commpress([value])

* value (布尔型)
* Returns Socket

设置修改器,是否对向服务器传输的数据进行压缩。默认为**true**,即压缩。

socket.compress(false).emit(‘an event’, { some: ‘data’ });


socket.close()

* Returns Socket

手动关闭客户端对服务器的链接

socket.disconnect()

用法同 **socket.close()**。

Event: 'connect'

连接成功后执行该函数。

socket.on(‘connect’, () => {
// …
});

// note: you should register event handlers outside of connect,
// so they are not registered again on reconnection
socket.on(‘myevent’, () => {
// …
});


Event: 'connect_error'

* error (对象) 错误对象

连接错误触发事件处理器。

socket.on(‘connect_error’, (error) => {
// …
});


Event: 'disconnect'

* reason (字符串) 服务器或客户端丢失连接的原因

丢失连接时触发时间处理器

socket.on(‘disconnect’, (timeout) => {
// …
});


Event: 'reconnect'

* attempt (字符串) 重连次数

成功的重连时触发时间处理器

socket.on(‘reconnect’, (timeout) => {
// …
});


Event: 'reconnect_attempt'

* attempt (字符串) 重连次数

成功的重连时触发时间处理器

socket.on(‘reconnect_attempt’, (timeout) => {
// …
});


Event: 'reconnecting'

* attempt (字符串) 尝试重连次数

尝试重连时触发时间处理器

socket.on(‘reconnecting’, (timeout) => {
// …
});


Event: 'reconnect_error'

* attempt (字符串) 错误对象

重连错误时触发时间处理器

socket.on(‘reconnect_error’, (timeout) => {
// …
});


Event: 'reconnect_failed'

socket.on(‘reconnect_failed’, (timeout) => {
// …
});


Event: 'ping'

socket.on(‘ping’, (timeout) => {
// …
});


Event: 'pong'

* ms (数值型) 自ping到pong经历的毫秒数

socket.on(‘pong’, (timeout) => {
// …
});


继续阅读:[[译] socket.io官方文档·上篇](/article/socket-io-official-document-translate-part-one/)
原文地址:https://www.cnblogs.com/wjlbk/p/12633330.html