我是套接字的新手
我正在运行一个快速的网络服务器,其客户端正在使用socket.io。
基本上,每当有人点击我的一个帖子请求时,我想向我的客户发出一个结果,表明帖子请求被点击了。我认为它看起来像这样。
节点服务器
const app = express();
app.post('/makeOrder', function(req, res){
// Do some database logic that pushes the order into my database
// This is where I'm stuck.
// I want to notify the client that the order is placed.
// Would it look something like this?
io.in('kitchenSocket').emit('order-placed', 'An order has been placed!');
// Last send something to finish the request
res.send({test:"order placed"})
}
网络客户端
<script src="/socket.io.js"></script>
<script>
// What I currently have
var socket = io.connect('http://localhost:5554/kitchenSocket');
socket.on('order-placed', function (data) {
alert("an order has been placed:" + data)
});
</script>
如何让它在快速端点上发出消息?
答案 0 :(得分:1)
以下是一些代码,我必须做一些非常相似的事情,你需要添加一些更改,但这是一个大致的想法。主要区别在于我使用的是Redis服务器。如果这有用,或者您有后续问题,请告诉我。
服务器端代码
var io = require('socket.io').listen(app);
var redis = require('socket.io-redis');
io.adapter(redis({ host: config.redis, port:config.redisPort }));
//sets allowed origions
io.set("origins", "*:*");
let sockectObj = [data to be sent]
io.emit('notification', sockectObj);
前端代码
this.socket = io(CONFIG.socket, { query: [naming parameter] });
this.socket.on("notification", function (resObj) {
//Action to be performed
}.bind(this));
答案 1 :(得分:1)
为任何想要它的人提供Express Express代码:
节点服务器
app.post('/makeOrder', function(req, res){
// Do logic
var javascriptObject = {};
io.emit("someName", javascriptObject);
res.send({test:"Some message"});
}
<强>客户端强>
<script src="/socket.io.js"></script>
<script>
this.socket = io('/', {transports: ['websocket']});
socket.on('someName', function (data) {
// Do client stuff
});
</script>