在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ SSE后臺(tái)服務(wù)器怎么結(jié)合使用路由

SSE后臺(tái)服務(wù)器怎么結(jié)合使用路由

我現(xiàn)在前端可以通過(guò)EventSource發(fā)送并接受消息,后臺(tái)使用http模塊構(gòu)建數(shù)據(jù)流,但是怎么結(jié)合express模塊寫(xiě)路由啊
前端
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Title</title>

</head>
<body>
<button>點(diǎn)擊</button>
</body>
<script>

var source = new EventSource("http://localhost:8080");
source.addEventListener("message",function (e) {
    console.log(e.data)
},false);
source.onopen = function () {
    console.log("連接已建立")
}
source.onerror = function (err) {
    console.log(err)
}

</script>
</html>
node端
var app = require("express")();
// var http = require("http").Server(app);
var http = require("http")
var server = http.Server(app);
var fs = require('fs');
http.createServer(function (req, res) {

    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");
    res.write("data: " + (new Date()) + "\n\n");

    var interval = setInterval(function() {
        res.write("data: " + (new Date()) + "\n\n");
    }, 1000);

    req.connection.addListener("close", function () {
        clearInterval(interval);
    }, false);

}).listen(8080,function () {

console.log("【8080】服務(wù)器啟動(dòng)成功")

});

回答
編輯回答
胭脂淚

EventSource 接口用于接收服務(wù)器發(fā)送的事件, 和路由是沒(méi)有關(guān)系的。不太明白你是要做什么,而且EventSource這種技術(shù)實(shí)際上已經(jīng)過(guò)時(shí)了,而且瀏覽器兼容也不好。

另外,你的express用的也似乎不太好,建議先到官網(wǎng)看看使用教程,http://expressjs.com/en/guide...

真心建議EventSource就別用了,Socket.io比他好幾萬(wàn)倍,https://socket.io/

2017年2月2日 05:33