首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点中的event-stream :在控制台中工作正常,但不写入流

节点中的event-stream :在控制台中工作正常,但不写入流
EN

Stack Overflow用户
提问于 2019-01-13 07:30:17
回答 1查看 325关注 0票数 1

我想将事件流式传输到localhost/czml -它在控制台或get请求窗口中工作得很好。但我不能将这些变量流式传输到页面,因为req.query总是以未定义结束

我是一个该死的编程新手,大多数时候我都不知道我在做什么(这就是为什么代码如此糟糕……)。我通过试验和错误得到了代码,主要是通过从某个地方复制得到的

代码语言:javascript
复制
var express = require('express'),
    fs = require('fs'),
    morgan = require('morgan'),
    path = require('path'),
    os = require('os'),
    http = require('http');

    const app = express();
    const EventEmitter = require('events');
    const stream = new EventEmitter();
    var czmlstream = fs.createWriteStream('czml.czml',{flags: 'a'});


    app.get('/czml', function (req, res, next) {
    //don't log favicon
    if (req.url === '/favicon.ico'){
        res.end();
        return;
    }

    //only log GET and set to stream
    if (req.method === 'GET' ) {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });

    function createCzml() {
        //get the query value from the request
        var id = req.query.id;
        var lon = parseInt(req.query.lon);
        var lat = parseInt(req.query.lat);
        var alt = parseInt(req.query.alt);

        // custom json format for czml file
        var entity = {
            "id": id,
            "position": {
                "cartographicDegrees": [lat, lon, alt]
            },
            "point": {
                "color" : {"rgba": [0,0,255,255]},
            "pixelSize": 20
            }
        };
        return entity;

    }   
        //first 2 lines for the event stream
    res.write('event: czml\n');
    res.write('data:' + JSON.stringify({ "id":"document", "version":"1.0" })+   
    '\n\n');

    //always tells me that 10 listeners are added .... ?
    stream.setMaxListeners(0);

    //stream.on(req) = emit event on get request?
    stream.on('req', function() {
        res.write('event: czml\n');
        res.write('data:' +JSON.stringify(createCzml)+ '\n\n'); //this 
    doesn't work
    });
    //not sure why this is needed
    stream.emit('req');
    }else{
        res.WriteHead(405, {'Content-Type': 'text/plain'});
        res.end('No GET Request - not allowed');
    }

    //morgan(format, {stream: czmlstream})(req,res,next);   
    }).listen(8000);
    console.log('Server running');

我想要实现的是:有人向localhost/czml/?id=1&lon=-40&lat=30&alt=5000 =>发送get请求,这些查询被解析并以事件流的形式发送到localhost/任何地方,格式为:

事件: czml数据:{json}

我就快完成了(即使代码很糟糕)--这是我必须向localhost/写那些烦人的查询的最后一部分。现在,它在控制台中记录一切正常,但未定义被写入到localhost/诸如此类……

如果您能为我指明正确的方向,我将不胜感激-尽管如此,请记住,我需要简单而好的解释;)

EN

回答 1

Stack Overflow用户

发布于 2019-01-17 18:28:21

好的,我自己解决了这个问题,只是为了给其他新手参考:

这基本上是一个this示例,只有get请求的侦听器(据我所知)

代码语言:javascript
复制
    // most basic dependencies
var express = require('express')
  , http = require('http')
  , os = require('os')
  , path = require('path')
  , url = require('url')
  , fs = require('fs');

// create the app
var app = express();

// configure everything, just basic setup
//app.set('port', process.env.PORT || 8000);
app.use(function(req, resp, next) {
  resp.header("Access-Control-Allow-Origin", "*");
  resp.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// Serve the www directory statically
app.use(express.static('www'));

//---------------------------------------
// Handle Get request and event-stream every second
//---------------------------------------
var openConnections = [];

var id, lon, lat, alt;

app.get('/czml', function(req, res, next) {
    //don't log favicon
    if (req.url === '/favicon.ico'){
        res.end();
        return;
    } else {

    var queryData = url.parse(req.url, true).query;
    id = queryData.id;
    lon = queryData.lon;
    lat = queryData.lat;
    alt = queryData.alt;

    req.socket.setTimeout(2 * 60 * 1000);

    // send headers for event-stream connection
    // see spec for more information
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });
    res.write('\n');

    // push this res object to our global variable
    openConnections.push(res);

    // send document packet
    res.write('event: czml\ndata:' + JSON.stringify({ "id":"document", "version":"1.0" })+   '\n\n');

    // When the request is closed, e.g. the browser window
    // is closed. We search through the open connections
    // array and remove this connection.
    req.on("close", function() {
        var toRemove;
        for (var j =0 ; j < openConnections.length ; j++) {
            if (openConnections[j] == res) {
                toRemove =j;
                break;
            }
        }
        openConnections.splice(j,1);
    });
    next();
    }
}).listen(8000);

function createMsg() {
        var entity = {
            "id" : id,
            "position" : {
                "cartographicDegrees": [lon,lat,alt]
            },
            "point" : { 
                "color" : {
                    "rgba" : [0,0,255,255]
                },
                "pixelSize" : 15
            }

        };
        return JSON.stringify(entity);;
    }

setInterval(function() {
    // we walk through each connection
    openConnections.forEach(function(res) {
        // send doc
        res.write('event: czml\n');
        res.write('data:' + createMsg() +   '\n\n');
    });
}, 1000);

我不知道这是如何工作的,所以-上面并不是我问题的真正答案-更多的是一种变通方法。但它可以工作,所以我想这没问题:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54164836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档