首页 > 代码库 > websocket

websocket

什么是websocket?

不错的介绍:https://www.zhihu.com/question/20215561

websocket是一种持久化的协议,实现了浏览器和服务端的全双工通信;

握手阶段与HTTP协议相同,返回状态码101(switching protocols);

握手阶段完成之后,按照websocket协议进行通信

 

应用场景:

浏览器与服务端需要实时通信的场景,以前的解决方式:ajax轮询、HTTP长连接、Flash等。

 

实现:

浏览器端

const ws = new WebSocket(‘ws://localhost:8080‘);

ws.onopen = function (evt) {
    console.log(‘connection open...‘);
    ws.send(‘hello websocket‘);
}

ws.onmessage = function (evt) {
    console.log(‘frontend received: ‘ + evt.data);
}

ws.onclose = function (evt) {
    console.log(‘connection closed...‘);
}

 

技术分享

 

node端

首先需要安装library:

  • ws
  • websocket-node
  • socket.io
  • engine.io
  • sockjs 

 以ws为例:

const WebSocket = require(‘ws‘);

const ws = new WebSocket.Server({port: 8080});

ws.on(‘connection‘, function (ws) {
    ws.on(‘message‘, function (msg) {
        console.log(‘backend received: ‘+ msg);
    })

    ws.send(‘something‘);

})

 

websocket