国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

socket.io 客戶端 API

2018-10-16 18:50 更新

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


  • (數(shù)值型)

表示協(xié)議版本號。

io(url[, options])


  • url (字符串)默認的指向widnow.location
  • option (Object)forceNew (布爾型)是否重用當前已存在的鏈接。
  • Return Socket

使用給定的URL創(chuàng)建一個新的Manager,并且嘗試重用一個已存在的Manager等待隨后調用,除非multiplex的選項為false,作用同force new connection:true或者forceNew: true。

一個新的socket實例將返回命名空間指定的socket,該命名空間由URL指定,默認的為 / 。舉個栗子,如果url為http://localhost/users,則將會對http://localhost進行傳輸連接,并且Socket.IO連接將會對/users建立連接。

你也也可以提供查詢參數(shù),直接將查詢參數(shù)添加到url上即可:

http://localhost/users?token=abc

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

初始化示例


使用多路復用


默認的,當連接道不同的命名空間后一個單一的鏈接將會被使用。

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

注意:重用相同的命名空間將會創(chuàng)建兩個連接:

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>

命名空間將會作為數(shù)據(jù)的一部分被發(fā)送。

攜帶查詢參數(shù)

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握手信號不信任自定義的請求頭(詳細信息可以閱讀 WebSocket protocol RFC

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傳輸時

默認的,長輪詢連接會被首次創(chuàng)建,隨后升級到更好的傳輸方式(比如WebSocket)。

如果你喜歡挑戰(zhàn)性,這一部分可以被跳過。

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'];
});

攜帶自定義的解析器

默認的解析器(詳細內容查閱這里Socket.IO custom parsers

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.ioreconnection (布爾型)是否自動重新建立連接,默認為truereconnectionAttempts (Number) 嘗試重連的次數(shù),默認為無限次reconnectionDelay (數(shù)值型) 重尋創(chuàng)建連接的延遲時長,默認為1000毫秒,受randomizationFactor正負加減的影響。比如默認的初始化延遲將在500至1500毫秒之間。reconnectionDelayMax (數(shù)值型)最大的重連等待時間,默認為5000毫秒。每一次嘗試都會以兩倍的增量增加重連的時間。randomizationFactor (數(shù)值型)默認為0.5,最小為0,最大為1.timeout (數(shù)值型) connect_error和connect_timeout事件觸發(fā)前的延遲時間,默認為20000毫秒。autoConnect (布爾型) 如果設置為fasle,你不得不手動調用manage.open函數(shù)。query (對象):當連接到一個命名空間,額外的查詢參數(shù)將被發(fā)送(隨后可以到服務器端查找socket.handshake.query對象)。parser (解析器):默認的為一個Parser實例,詳情查看socket.io-parserReturn Manager

這一選項同樣可通過engine.io-client初始化,查看參數(shù)

manager.reconnection([value])


  • value (布爾型)
  • Return Manager | Boolean

設置reconnection選項,或者如果沒有傳遞參數(shù)則直接返回它。

manager.reconnectionAttempts([value])


  • value (數(shù)值型)
  • Return Manager | Number

設置reconnectionAttempts選項,或者當沒有參數(shù)時直接返回。

manager.reconnectionDelay([value])


  • value (數(shù)值型)
  • Return Manager | Number

設置reconnectionDelay選項,或者當沒有參數(shù)時直接返回。

manager.reconnectionDelayMax([value])


  • value (數(shù)值型)
  • Return Manager | Number

設置reconnectionDelayMax選項,或者當沒有參數(shù)時直接返回。

manager.timeout([value])


  • value (數(shù)值型)
  • Return Manager | Number

設置timeout選項,或者當沒有參數(shù)時直接返回。

manager.open([callback])


  • callback (Function)
  • Return Manager

如果manager使用autoConnect初始化為false,嘗試運行一個新的連接。

這個回調函數(shù)參數(shù)時可選擇的,并且將會在錯誤或者成功后被執(zhí)行一次。

manager.connect([callback])


同**manager.open([callbakc])

manager.socket(nsp, options)


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

使用給定的命名空間創(chuàng)建一個新的Socket連接。

Event: 'connect_error'


  • error (對象) 錯誤對象

觸發(fā)連接錯誤事件。

Event: 'connect_timeout'


觸發(fā)連接超時事件

Event: 'reconnect'


  • attempt (數(shù)值型)嘗試重新連接的次數(shù)

觸發(fā)成功連接的事件

Event: 'reconnect_attempt'


觸發(fā)嘗試重新連接

Event: 'reconnecting'


  • attempt (數(shù)值型) 重新連接嘗試次數(shù)

觸發(fā)成功重新連接事件

Event: 'reconnect_error'


  • error (對象)錯誤對象

觸發(fā)當在reconnectionAttempts次數(shù)內無法重新連接的錯誤事件

Event: 'ping'


當請求ping發(fā)送到服務器端時。

Event: 'pong'


  • ms (數(shù)值型) 自ping至pong經(jīng)過的毫秒數(shù)

當接受到服務器端的pong時觸發(fā)。

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

發(fā)送一個message事件,詳細查看socket.emit(eventName[, ...args][, ack]).

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


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

通過提供的name時間名稱向socket標志發(fā)送事件,任何其他的參數(shù)都可被包含,所有可被序列化的數(shù)據(jù)結構都支持,包括Buffer。

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

ack參數(shù)將用來響應服務器用來確認消息的應答。

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(用來移除一個事件監(jiān)聽器)。

socket.commpress([value])


  • value (布爾型)
  • Returns Socket

設置修改器,是否對向服務器傳輸?shù)臄?shù)據(jù)進行壓縮。默認為true,即壓縮。

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

socket.close()


  • Returns Socket

手動關閉客戶端對服務器的鏈接

socket.disconnect()


用法同 socket.close()。

Event: 'connect'


連接成功后執(zhí)行該函數(shù)。

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 (對象) 錯誤對象

連接錯誤觸發(fā)事件處理器。

socket.on('connect_error', (error) => {
  // ...
});

Event: 'disconnect'


  • reason (字符串) 服務器或客戶端丟失連接的原因

丟失連接時觸發(fā)時間處理器

socket.on('disconnect', (timeout) => {
  // ...
});

Event: 'reconnect'


  • attempt (字符串) 重連次數(shù)

成功的重連時觸發(fā)時間處理器

socket.on('reconnect', (timeout) => {
  // ...
});

Event: 'reconnect_attempt'


  • attempt (字符串) 重連次數(shù)

成功的重連時觸發(fā)時間處理器

socket.on('reconnect_attempt', (timeout) => {
  // ...
});

Event: 'reconnecting'


  • attempt (字符串) 嘗試重連次數(shù)

嘗試重連時觸發(fā)時間處理器

socket.on('reconnecting', (timeout) => {
  // ...
});

Event: 'reconnect_error'


  • attempt (字符串) 錯誤對象

重連錯誤時觸發(fā)時間處理器

socket.on('reconnect_error', (timeout) => {
  // ...
});

Event: 'reconnect_failed'


socket.on('reconnect_failed', (timeout) => {
  // ...
});

Event: 'ping'


socket.on('ping', (timeout) => {
  // ...
});

Event: 'pong'


  • ms (數(shù)值型) 自ping到pong經(jīng)歷的毫秒數(shù)
socket.on('pong', (timeout) => {
  // ...
});


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號