【问题标题】:Real-time database view on HTML page with Socket.io使用 Socket.io 在 HTML 页面上实时查看数据库
【发布时间】:2018-11-18 10:38:06
【问题描述】:

我有一个树莓派,它不断通过 PHP 将数据推送到 MySQL 数据库。我正在尝试创建一个网站,我可以在其中实时查看该数据库的内容。

我一直在关注本教程:http://markshust.com/2013/11/07/creating-nodejs-server-client-socket-io-mysql,它显示了一个使用 socket.io 实现此目的的示例。这在 2 个客户端上运行良好,当我添加一个新注释时,它会在两个浏览器上更新。问题是当我从 mysql CLI 手动将记录添加到数据库时,它不会更新。我猜这是因为没有排放发生。我该如何实施?

Server.js:

var mysql = require('mysql')
// Let’s make node/socketio listen on port 3000
var io = require('socket.io').listen(3000)
// Define our db creds
var db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node'
})

// Log any errors connected to the db
db.connect(function(err){
    if (err) console.log(err)
})

// Define/initialize our global vars
var notes = []
var isInitNotes = false
var socketCount = 0

console.log("connected");

io.sockets.on('connection', function(socket){
    // Socket has connected, increase socket count
    socketCount++
    // Let all sockets know how many are connected
    io.sockets.emit('users connected', socketCount)

    socket.on('disconnect', function() {
        // Decrease the socket count on a disconnect, emit
        socketCount--
        io.sockets.emit('users connected', socketCount)
    })

    socket.on('new note', function(data){
        // New note added, push to all sockets and insert into db
        notes.push(data)
        io.sockets.emit('new note', data)
        // Use node's db injection format to filter incoming data
        db.query('INSERT INTO notes (note) VALUES (?)', data.note)
    })

    // Check to see if initial query/notes are set
    if (! isInitNotes) {
        // Initial app start, run db query
        db.query('SELECT * FROM notes')
            .on('result', function(data){
                // Push results onto the notes array
                notes.push(data)
            })
            .on('end', function(){
                // Only emit notes after query has been completed
                socket.emit('initial notes', notes)
            })

        isInitNotes = true
    } else {
        // Initial notes already exist, send out
        socket.emit('initial notes', notes)
    }
})

索引.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
    // Connect to our node/websockets server
    var socket = io.connect('http://localhost:3000');

    // Initial set of notes, loop through and add to list
    socket.on('initial notes', function(data){
        var html = ''
        for (var i = 0; i < data.length; i++){
            // We store html as a var then add to DOM after for efficiency
            html += '<li>' + data[i].note + '</li>'
        }
        $('#notes').html(html)
    })

    // New note emitted, add it to our list of current notes
    socket.on('new note', function(data){
        $('#notes').append('<li>' + data.note + '</li>')
    })

    // New socket connected, display new count on page
    socket.on('users connected', function(data){
        $('#usersConnected').html('Users connected: ' + data)
    })

    // Add a new (random) note, emit to server to let others know
    $('#newNote').click(function(){
        var newNote = 'This is a random ' + (Math.floor(Math.random() * 100) + 1)  + ' note'
        socket.emit('new note', {note: newNote})
    })
})
</script>
<ul id="notes"></ul>
<div id="usersConnected"></div>
<div id="newNote">Create a new note</div>

【问题讨论】:

标签: mysql websocket socket.io


【解决方案1】:

这类似于a previous question,似乎没有简单的方法可以用 MySQL 做到这一点。

如果你处于开发的早期阶段,你没有绑定到 MySQL,那么我会指出你可以用 postgresql 解决这个问题:

  • 通过 PDO 库从 PHP 推送(参见 docs)。
  • 在 Raspberry Pi 上运行。
  • 可以通过触发器上的pg_notify 检测从命令行任意位置推送的更新(请参阅docs)。
  • 可以通过 pg 包使用 NodeJS 订阅更新。

在技术层面上这是可行的,但数据库通常不如消息传递系统高效(注意Database-as-IPC anti-pattern)。当事情发生时,PHP 客户端也可以通过消息队列、UDP 套接字或其他方式发出自己的通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多