sakahiro0911
sakahiro0911

Reputation: 69

When doing websocket with vapor 3.0.8, the connection immediately becomes timeout

Currently, we are creating a server application (Deploy to VaporCloud) that communicates browser's JavaScript and WebSocket with Vapor 3.0.8 and Swift4.1. In that case, although we can connect websocket, even if we are not leaving the message as it is, onClose will occur on the JavaScript side in about 30 seconds and the connection will be lost. How can we maintain a connection?

[Server side source Sources/App/configure.swift)]

    public func configure(_ config: inout Config, _ env: inout Environment, _ 
services: inout Services) throws {
        let wss = NIOWebSocketServer.default() 
        wss.get(at:["chat"], use:{ ws,req in
          ws.onText({ (ws, text) in
          .....    
          ws.send("test")
          .....
        })
        .....
        })   
        services.register(wss, as: WebSocketServer.self)
        .....

[Javascript side source]

ws = new WebSocket('wss://hostname');
ws.onopen = function() {
    .....
    ws.send("test connect");
};
$('form').on('submit', function(e) {
  e.preventDefault();
  ws.send("test");
});
ws.onmessage = function(event) {
  console.log("data=" + event.data);
  .....
}
ws.onclose = function (e) {
  console.log("Close Code = " + e.code); // return 1006
  console.log("Close Reason = " + e.reason); // null
  .....
}

Upvotes: 1

Views: 830

Answers (2)

Sameer Jagtap
Sameer Jagtap

Reputation: 156

To keep the connection alive, you can schedule repeated task with a fixed delay:

socket.eventLoop.scheduleRepeatedTask(initialDelay: .seconds(5), delay: .seconds(10)) { task -> Void in
    guard !socket.isClosed else {
        task.cancel()
        return
    }
    socket.send(raw: UUID().uuidString, opcode: .ping)
}

Upvotes: 0

joscdk
joscdk

Reputation: 534

The Vapor Cloud loadbalancers have a timeout in place, that will close the connection automatically.

In theory you should be able to send an occasional ping packet from either the backend or the client, which will keep the connection open.

Tbh. I havn't tried it personally, but it should work.

(There are an example here, randomly found it, so i have not tried it out :) http://www.jstips.co/en/javascript/working-with-websocket-timeout/ )

Upvotes: 1

Related Questions