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

来源:互联网 发布:配音软件 语气 编辑:程序博客网 时间:2024/06/05 21:52

首先我们需要安装socket模块

安装命令: npm install socket.io

编辑前台页面:index.html

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

服务端的:index.js

volatile 意思大概是说,当服务器发送数据时,客户端因为各种原因不能正常接收,比如网络问题、或者正处于长连接的建立连接阶段。此时会让我们的应用变得 suffer,那就需要考虑发送 volatile 数据。

var app = require('http').createServer(handler),    io = require('socket.io').listen(app),    fs = require('fs');//当前在线人数var onlineCount = 0;function handler (req, res) {    fs.readFile(__dirname + '/index.html',        function (err, data) {            if (err) {                res.writeHead(500);                return res.end('Error loading index.html');            }            res.writeHead(200);            res.end(data);        });}//连接事件io.sockets.on('connection', function (socket) {    console.log('有新用户进入...');    //叠加当前在线人数    onlineCount++;    var tweets = setInterval(function () {            socket.volatile.emit('onlinenums', {nums : onlineCount});    }, 1000);    console.log('当前用户数量:'+onlineCount);    //客户端断开连接    socket.on('disconnect', function() {        if(onlineCount > 0 ){            //当前在线用户减一            onlineCount--;            console.log('当前用户数量:'+onlineCount);        }    });});//启动HTTP服务,绑定端口3000app.listen(3000, function(){    console.log('listening on *:3000');});


运行index.js:


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


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


服务端打印日志信息:


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

0 0
原创粉丝点击