nodejs 使用socket.io与网页实时数据交互

谁践踏了优雅 2022-07-29 09:25 189阅读 0赞

首先我们需要安装socket模块

安装命令: npm install socket.io

编辑前台页面:index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8">
  5. <title>统计在线人数</title>
  6. <script src="http://localhost:3000/socket.io/socket.io.js"></script>
  7. <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  8. <script type="text/javascript">
  9. // 创建websocket连接
  10. var socket = io.connect('http://localhost:3000');
  11. // 把信息显示到div上
  12. socket.on('onlinenums', function (data) {
  13. $("#nums").html(data.nums);
  14. });
  15. </script>
  16. </head>
  17. <body>
  18. 当前在线人数:<span style="color: red;" id="nums">0</span>
  19. </body>
  20. </html>

服务端的:index.js

volatile 意思大概是说,当服务器发送数据时,客户端因为各种原因不能正常接收,比如网络问题、或者正处于长连接的建立连接阶段。此时会让我们的应用变得 suffer,那就需要考虑发送 volatile 数据。
  1. var app = require('http').createServer(handler),
  2. io = require('socket.io').listen(app),
  3. fs = require('fs');
  4. //当前在线人数
  5. var onlineCount = 0;
  6. function handler (req, res) {
  7. fs.readFile(__dirname + '/index.html',
  8. function (err, data) {
  9. if (err) {
  10. res.writeHead(500);
  11. return res.end('Error loading index.html');
  12. }
  13. res.writeHead(200);
  14. res.end(data);
  15. });
  16. }
  17. //连接事件
  18. io.sockets.on('connection', function (socket) {
  19. console.log('有新用户进入...');
  20. //叠加当前在线人数
  21. onlineCount++;
  22. var tweets = setInterval(function () {
  23. socket.volatile.emit('onlinenums', {nums : onlineCount});
  24. }, 1000);
  25. console.log('当前用户数量:'+onlineCount);
  26. //客户端断开连接
  27. socket.on('disconnect', function() {
  28. if(onlineCount > 0 ){
  29. //当前在线用户减一
  30. onlineCount--;
  31. console.log('当前用户数量:'+onlineCount);
  32. }
  33. });
  34. });
  35. //启动HTTP服务,绑定端口3000
  36. app.listen(3000, function(){
  37. console.log('listening on *:3000');
  38. });

运行index.js:

Center
启动web服务器,访问index.html:

Center 1

再打开一个窗口打开这个链接:

Center 2

服务端打印日志信息:

Center 3

node 的socket.io模块使用起来非常简单方便,把我们需要交互的实时信息推送到前端的页面。

发表评论

表情:
评论列表 (有 0 条评论,189人围观)

还没有评论,来说两句吧...

相关阅读