WebSocket 教程

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

  • webSocket

  • socket.io

  • socket.io.client

客户端的简单用法

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.");
}; 

客户端的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

服务端

var app = require(‘express‘)();
var server = require(‘http‘).Server(app);
var io = require(‘socket.io‘)(server);

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

客户端

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io(‘http://localhost‘);
  socket.on(‘news‘, function (data) {
    console.log(data);
    socket.emit(‘my other event‘, { my: ‘data‘ });
  });
</script>

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

WebSocket 教程

上一篇:CSS——选择器、字体样式、文本样式——第4天


下一篇:PHP的引用计数是什么意思?