我目前通过更新Node/Express/MongoDB应用程序
jQuery.ajax()
请求。
服务器响应被发送回ajax请求的成功处理程序,并在发送者的客户机上进行各种接口更改。
客户端
function update_database(parameters) {
$.ajax({
method: "POST",
url: "/api/v1/my_path",
data: parameters,
dataType: 'json',
cache: false,
headers: headers,
success: function(results) {
// perform interface changes
},
statusCode: {
500: function() {
console.log("that didn't work");
}
}
});
}
我想更新所有连接的客户端。
official socket.io cheatsheet
显示相关方法为:
// send to all clients except sender
socket.broadcast.emit('broadcast', 'hello friends!');
在上下文中
Broadcasting
剖面图
official tutorial
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.broadcast.emit('hi');
});
我该怎么做
socket.broadcast.emit
从路由处理程序的函数中?
broadcase.emit
在一个
io.on('connection')
由于变量
socket
尚未声明,但使用
io.on('连接')
每次我都想
插座.广播.发射
.
服务器端
// app setup
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// the route handler
app.route("/api/:api_version/my_path")
.post(api_my_post);
// the function
const api_my_post = (req, res) => {
// define the filter and update
var filter = { _id: o_id };
var update = { $set: { key: value } };
// perform the required database update
collection.findOneAndUpdate(filter, update, function(err, result) {
if (err) {
res.send(err);
} else {
// create an object to return
var response_json = { key: value, key_2: value_2 };
// return the object to the ajax success handler
res.json(response_json);
// return the object to all other connected clients
socket.broadcast.emit("ajax_response", response_json);
}
});
}
编辑:
下面的答案看起来很有希望,也相对简单,但似乎只迎合了
io.emit
场景而不是
脚本。
有没有可能
插座
插座.广播.发射
?:
https://stackoverflow.com/a/31277123
基本配置:
var app = require('express')();
var server = app.listen(process.env.PORT || 3000);
var io = require('socket.io')(server);
// next line is the money
app.set('socketio', io);
exports.foo = function(req,res){
// now use socket.io in your routes file
var io = req.app.get('socketio');
io.emit('hi!');
}