123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- #!/usr/bin/env node
- /**
- * Module dependencies.
- */
- const http = require('http');
- const SSE = require('sse');
- const url = require('url');
- const sseClient = require('../../models/sse_client');
- const order = require('../../db/models/order');
- const debug = require('debug')('shuiduoduo.server:server');
- require('../../utils/logger');
- const app = require('../app');
- const config = require('../config');
- const { clear } = require('console');
- /**
- * Get port from environment and store in Express.
- */
- const port = normalizePort(process.env.PORT || config.port || '3000');
- app.set('port', port);
- console.log(port);
- /**
- * Create HTTP server.
- */
- const server = http.createServer(app);
- /**
- * Listen on provided port, on all network interfaces.
- */
- server.listen(port, () => {
- const sse = new SSE(server);
- sse.on('connection', async client => {
- const req = url.parse(client.req.url, true);
- client.id = req.query.oid;
- // client.sendjson = data => {
- // client.send(JSON.stringify(data));
- // };
- const odata = await order.findOne({ where: { id: client.id } });
- if (!odata) {
- return client.close();
- }
- if (odata.status === config.ORDER_STATUS.已支付) {
- client.send('done');
- return client.close();
- }
- if (sseClient[client.id]) {
- sseClient[client.id].close();
- }
- sseClient[client.id] = client;
- client.on('close', () => {
- // clearTimeout(client.tick);
- delete sseClient[client.id];
- });
- client.tick = setTimeout(() => {
- if (sseClient[client.id]) {
- sseClient[client.id].close();
- }
- }, 1000 * 60 * 10);
- });
- });
- server.on('error', onError);
- server.on('listening', onListening);
- /**
- * Normalize a port into a number, string, or false.
- */
- function normalizePort(val) {
- const port = parseInt(val, 10);
- if (Number.isNaN(port)) {
- // named pipe
- return val;
- }
- if (port >= 0) {
- // port number
- return port;
- }
- return false;
- }
- /**
- * Event listener for HTTP server "error" event.
- */
- function onError(error) {
- if (error.syscall !== 'listen') {
- throw error;
- }
- const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
- // handle specific listen errors with friendly messages
- switch (error.code) {
- case 'EACCES':
- console.error(`${bind} requires elevated privileges`);
- process.exit(1);
- break;
- case 'EADDRINUSE':
- console.error(`${bind} is already in use`);
- process.exit(1);
- break;
- default:
- throw error;
- }
- }
- /**
- * Event listener for HTTP server "listening" event.
- */
- function onListening() {
- const addr = server.address();
- const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
- console.log(`Listening on ${bind}`);
- }
|