我尝试在客户端使用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()
}
以及处理post请求:
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()
}
}
问题是,在客户端,我接收到on Open通知,事件源的readyState传递到“Open”(1),但在onerror通知和readyState传递到“Connecting”(0)之后,我立即接收到。等等:连接,关闭,连接,关闭。。。因此,post请求永远不会执行。
我将感谢一些帮助,有一个代码,保持开放连接。
谢谢您,
诺图
最佳答案
Kitura目前不支持持久的、开放的HTTP连接。但是,您可以使用WebSocket而不是服务器通过HTTP发送事件来复制功能(您需要重写前端代码以使用WebSockets而不是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/