Socket 使用总结


Socket 是一种网络通信协议,很多高级功能都需要它。

当前常用的socket库有以下几个

  • webSocket

  • socket.io

  • socket.io.client

Socket.io 文档

websocket 客户端的简单用法

var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function(evt) { 
  console.log("Connection open ..."); 
  ws.send("Hello WebSockets!");
};

ws.onmessage = function(evt) {
  console.log( "Received Message: " + evt.data);
  ws.close();
};

ws.onclose = function(evt) {
  console.log("Connection closed.");
}; 

webSocket 客户端常用的API

WebSocket 构造函数

var ws = new WebSocket('ws://localhost:8080');

webSocket.readyState

switch (ws.readyState) {
  case WebSocket.CONNECTING:
    // do something
    break;
  case WebSocket.OPEN:
    // do something
    break;
  case WebSocket.CLOSING:
    // do something
    break;
  case WebSocket.CLOSED:
    // do something
    break;
  default:
    // this never happens
    break;
}

webSocket.onopen

ws.onopen = function () {
  ws.send('Hello Server!');
}

也可以使用

ws.addEventListener('open', function (event) {
  ws.send('Hello Server!');
});

webSocket.onclose

ws.onclose = function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
};

ws.addEventListener("close", function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
});

webSocket.onmessage

ws.onmessage = function(event) {
  var data = event.data;
  // 处理数据
};

ws.addEventListener("message", function(event) {
  var data = event.data;
  // 处理数据
});

webSocket.send()

ws.send('your message');

Socket.IO

服务端 初始化

const app = require('express')();
const server = require('http').Server(app);
const options = {}
const io = require('socket.io')(server,options);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

客户端



Socket.IO server options配置

服务端

const redisClient = require("redis").createClient();
const io = require('socket.io')(httpServer,{
  path: '/orderList/',
  //适配器
  adapter: require("socket.io-redis")({
    pubClient: redisClient,
    subClient: redisClient.duplicate()
  }),
  connectTimeout: 4500,
  //过期时间
  pingTimeout: 3000,
  //链接时间
  pingInterval: 25000,
  
  upgradeTimeout: 10000,
  //最大传输数据
  maxHttpBufferSize: (1MB) 1e6,
  //跨域
  cors: {
    origin: ["https://example.com", "https://dev.example.com"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  },
  //cookie
  cookie: {
    name: "my-cookie",
    httpOnly: true,
    sameSite: "strict",
    maxAge: 86400
  },
  //allowEIO3
  allowEIO3: true, // false by default
});

客户端

const socket = io('http://example.com',{
  path: '/orderList/'
});

socket.io的基本用法

io.on('connection', socket => {
  socket.emit('request', /* … */); // emit an event to the socket
  io.emit('broadcast', /* … */); // emit an event to all connected sockets
  socket.on('reply', () => { /* … */ }); // listen to the event
});

socket.io.client 的用法和socket.io的用法差不多