您可以使用 Node.js 来实现它。以下是一个工作代码示例。节点js:index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/", function (req, res) {
res.sendFile("index.html", {root: __dirname});
});
io.on("connection", function (socket) {
socket.on("notify", function (notification_request) {
io.emit('notify', JSON.stringify(notification_request));
});
});
http.listen(3000, function () {
console.log('listenting on 3000');
});
你之前的前端index.html</body>
<script>
var socket = io();
$('button').click(function () { //notify event triggered
socket.emit('notify', {notification-1: "message1", notification-2: "message2", notification-3: "message3"});
return false;
});
socket.on('notify', function (notification) {
var notifications = JSON.parse(notification); //process notication array
$('#notification-div').append(notifications); //display the notification here which is going to be reflected for all clients
});
</script>
在终端或 CLI 上运行 index.js 文件来激活服务器。并且不要忘记安装以下节点模块
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);