Socket.IO 是一个WebSocket库,可以在客户端和服务器之间实现低延迟、双向和基于事件的通信。它建立在 WebSocket 协议之上,并提供额外的保证,例如回退到 HTTP 长轮询或自动重新连接。
基本使用
安装socket.io
yarn add socket.io
新建js文件与html文件内容如下
var http = require('http');
var io = require('socket.io');
var server = http.createServer((req,res)=>{
});
server.listen(2183);
// 监听 connection
io.listen(server).on('connection',(user)=>{
setInterval(()=>{
user.emit('test','哥们我主动来了'+Math.random());
},1000);
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
// 引用脚本,固定写法
<script type="text/javascript" src='http://localhost:2183/%3C/code%3E%3C/pre%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3C/div%3E%20%20%20%20%20%20%20%20%3C/div%3E%20%20%20%20%3C/article%3E%20%20%3Cscript%3E%20%20%20%20$(function()%20%7B%20%20%20%20%20%20setTimeout(function%20()%20%7B%20%20%20%20%20%20%20%20var%20mathcodeList%20=%20document.querySelectorAll('.htmledit_views img.mathcode');
if (mathcodeList.length > 0) {
for (let i = 0; i < mathcodeList.length; i++) {
if (mathcodeList[i].complete) {
if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
var alt = mathcodeList[i].alt;
alt = '\\(' + alt + '\\)';
var curSpan = $('');
curSpan.text(alt);
$(mathcodeList[i]).before(curSpan);
$(mathcodeList[i]).remove();
}
} else {
mathcodeList[i].onerror = function() {
var alt = mathcodeList[i].alt;
alt = '\\(' + alt + '\\)';
var curSpan = $('');
curSpan.text(alt);
$(mathcodeList[i]).before(curSpan);
$(mathcodeList[i]).remove();
};
}
}
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}, 500)
});
09-29
1554
1554
10-16
1451
1451
09-14
1706
1706
03-17
1538
1538

本文介绍了Socket.IO库在实现低延迟、双向通信中的作用,它基于WebSocket并提供回退机制。通过示例展示了如何安装、设置服务器和客户端,进行消息推送和接收。此外,还讲解了如何广播消息给所有用户,以及处理用户断开连接的事件。最后,通过一个远程拖拽的例子进一步说明了Socket.IO的实时交互能力。

被折叠的 条评论
为什么被折叠?



