gpt4 book ai didi

swift - 服务器使用 Kitura 发送事件

转载 作者:行者123 更新时间:2023-11-28 06:27:05 27 4
gpt4 key购买 nike

我尝试做一个客户端-服务器应用程序,在客户端使用 Angular2/typescript 网站,在服务器端使用 Mac OSX 上的 Swift 中的 Kitura 服务器。在客户端,typescript 代码实例化了一个 EventSource 对象:

    this.eventSource = new EventSource(this.webSocketServerUrl);
this.eventSource.onopen = (event: Event): any => {
console.log("ServerNotificationsService.onopen - " + JSON.stringify(event) + " " + this.eventSource.readyState);
event.stopPropagation();
return null;
}
this.eventSource.onerror = (event: sse.IOnMessageEvent) => {
console.log("ServerNotificationsService.onerror - " + JSON.stringify(event) + " " + this.eventSource.readyState);
}
this.eventSource.onmessage = (event: Event): any => {
console.log("ServerNotificationsService.onmessage - " + JSON.stringify(event) + " " + this.eventSource.readyState);
event.stopPropagation();
return null;
}
console.log("ServerNotificationsService.constructor - " + this.eventSource.readyState);

在服务器端,我处理 GET 请求的代码如下所示:

router.get("/notifications") { request, response, next in 
response.headers.append("Access-Control-Allow-Origin", value: "*")

if((request.accepts(header: "Accept", type: "text/event-stream")) != nil)
{
response.headers.append("content-type", value: "text/event-stream; charset=utf-8")
response.headers.append("cache-control", value: "no-cache")
response.headers.append("connection", value: "keep-alive")
try response.end()
Logger.sharedInstance.verbose(msg: "Request GET /notifications OK")
}
else
{
try response.status(.internalServerError).end()
Logger.sharedInstance.verbose(msg: "Request GET /notifications internalServerError")
}

next()
}

并处理发布请求:

router.post("/notifications") { request, response, next in
Logger.sharedInstance.verbose(msg: "Request POST /notifications ...")
response.headers.append("Access-Control-Allow-Origin", value: "*")
response.headers.append("content-type", value: "text/event-stream; charset=utf-8")
response.headers.append("cache-control", value: "no-cache")
response.headers.append("connection", value: "keep-alive")

while (true)
{
// wait here 5s. for the <nextMessage>
response.send(<nextMessage>)
try response.end()
Logger.sharedInstance.verbose(msg: "Request POST /notifications OK")
next()
}
}

问题是,在客户端,我收到 onopen 通知,事件源的 readyState 传递给“Open”(1),但我在 onerror 通知后立即收到,readyState 传递给“Connecting”(0)。依此类推:连接、关闭、连接、关闭……因此,发布请求永远不会执行。

我将感谢一些帮助,以获得维护开放连接的代码。

谢谢,

诺克斯

最佳答案

Kitura 当前不支持持久的、开放的 HTTP 连接。但是,您可以使用 WebSocket 而不是通过 HTTP 服务器发送的事件来复制功能(您需要重写前端代码以使用 WebSocket 而不是 EventSource): https://github.com/IBM-Swift/Kitura-WebSocket

示例 Kitura-WebSocket 应用程序可以在这里找到: https://github.com/IBM-Swift/Kitura-Chat-Server

关于swift - 服务器使用 Kitura 发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552672/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com