Nodejs 實現長連接,SSE, 服務端代碼

// 監聽方

function (req, res) {
  var fileName = "." + req.url;
  if (fileName === "./stream") {
    res.writeHead(200, {
      "Content-Type":"text/event-stream",
      "Cache-Control":"no-cache",
      "Connection":"keep-alive",
      "Access-Control-Allow-Origin": '*',
    });
    res.write("retry: 10000\n");
    res.write("event: connecttime\n");

	this.eventCenter.addListener(req.queryString.id, function(res){
		if(res.data){
			req.write('data: ' + data);
		} else {
			req.end();
		}
	
	});
}
}



// 事件中心
EventCenter = function () {
	
	this.eventList = {};
	this.eventEntyties = []

	this.createEvent = function(){
		const event = new Event(this);
		this.eventEntyties.push(event);
		const eventId = event.id;
		this.eventList.eventId = [];
		return event;
	},

	this.addListener = function(eventId, cb){
		this.eventList[eventId].push(cb);
	}

	this._checkEvent = function(){
		this.eventEntyties.map(event => {
			if(timoout(event)){
				delete event;
			}
		})
		
	}

	setInterval(this._checkEvent, 1000)

	
}

Event = function(center){
	this.id = '',
	this.center = center;
}

Event.prototype.done = function(){
	this.center.eventList[this.id].map(fn => fn.call({}, {}));
	delete this.center.eventList[this.id];
}

Event.prototype.emit = function(data){
	if(this.center.eventList[this.id]){
		this.center.eventList[this.id].map(fn => fn.call({}, data))
	} else {
		throw Error('事件不存在,或者超時');
	}
	
}

// 事件生成和觸發方
var event = this.eventCenter.createEvent({
	// 事件參數
	timeout: 20* 1000, // 20分鐘

});
while(){
	var txt = '';
	try{
		event.emit({data: txt});
	}
	catch(e){

	}
	
}

event.done();
相關文章
相關標籤/搜索