websocket
2021-06-28 12:05
标签:console const question host new closed library div 安装 不错的介绍:https://www.zhihu.com/question/20215561 websocket是一种持久化的协议,实现了浏览器和服务端的全双工通信; 握手阶段与HTTP协议相同,返回状态码101(switching protocols); 握手阶段完成之后,按照websocket协议进行通信 应用场景: 浏览器与服务端需要实时通信的场景,以前的解决方式:ajax轮询、HTTP长连接、Flash等。 实现: 浏览器端 node端 首先需要安装library: 以ws为例: websocket 标签:console const question host new closed library div 安装 原文地址:http://www.cnblogs.com/zmiaozzz/p/7143602.html什么是websocket?
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...‘);
}
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‘);
})