Answer the question
In order to leave comments, you need to log in
How to make expressjs process identical requests at the same time?
I took the code from the examples, but I got such a problem, if you call subscribe and subscribe again, then only the first one will subscribe, when I send send, then the message is sent to the first subscribe , and the second one only after that subscribes and receives the second message, and in a circle general
'use strict';
const express = require('express');
const parser = require('body-parser');
const events = require('events');
const dispatcher = new events.EventEmitter();
const app = express();
app.post('/send', parser.json(), (req, res) => {
dispatcher.emit('message', JSON.stringify(req.body));
res.set('Content-Type', 'text/plain;charset=utf-8');
res.end('ok');
});
app.get('/send', (req, res) => {
dispatcher.emit('message', "fkfkf");
res.set('Content-Type', 'text/plain;charset=utf-8');
res.end('ok');
});
app.get('/subscribe', (req, res) => {
console.log("subscribe")
res.set('Content-Type', 'text/plain;charset=utf-8');
res.set('Cache-Control', 'no-cache, must-revalidate');
dispatcher.once('message', message => setTimeout(()=>res.end(message),Math.random() * (1000 - 0)));
});
app.use(express.static('./client'));
app.listen(4000);
Answer the question
In order to leave comments, you need to log in
Put res.flushHeaders() before dispatcher.once - then it works with tabs)))
The browser does not open the next connection until everything is clear with this. Probably not to ddos
And so everything is logical, you first accept a request from the client, and then hang up an event on the emitter (dispatcher.once). And, apparently, they wanted the opposite. Here it also works on even requests.
But to be honest, I did not understand at all what you are trying to do with this code.
well, crap in your code.
1. ONCE event which is executed 1 time and the subscription is forgotten.
From what I see. You first turn on the subscription, then send two "emits", and the subscription url returns you only 1.
2. Why be surprised?
3. Making a subscription as a longpool connection is generally nonsense IMHO (well, or at least information from events should be written not through end(), but through instant output and give text in parts, but this is crap.
4. There is socket.io for events, it is great friends with express.
forget about simultaneously, asynchronously does not mean simultaneously. And yes, only 1 request is processed at a time.
UPD:
And even if there is .on, the end(text) method will complete your holiday.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question