Skip to content

Commit

Permalink
#4: Add web sockets for connection events
Browse files Browse the repository at this point in the history
  • Loading branch information
lika-vorobeva committed Oct 5, 2022
1 parent c58e564 commit 699c17c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ import Vapor

class DVPNServer: ObservableObject {
let app: Application
private var currentClientConnection: WebSocket?
private let context: CommonContext

init(context: CommonContext) {
app = Application(.development)
self.context = context
Config.setup()

configure(app)
}
Expand All @@ -25,7 +27,12 @@ extension DVPNServer {
do {
let api = app.grouped(.init(stringLiteral: ClientConstants.apiPath))
try api.register(collection: NodesRouteCollection(context: context))
try api.register(collection: TunnelRouteCollection(context: context))
try api.register(collection:
TunnelRouteCollection(
model: ConnectionModel(context: context),
delegate: self
)
)
try app.start()
} catch {
fatalError(error.localizedDescription)
Expand All @@ -40,5 +47,30 @@ extension DVPNServer {
private func configure(_ app: Application) {
app.http.server.configuration.hostname = ClientConstants.host
app.http.server.configuration.port = ClientConstants.port

configureConnection()
}

private func configureConnection() {
app.webSocket("echo") { [weak self] req, client in
client.pingInterval = .seconds(5)
self?.currentClientConnection = client

client.onClose.whenComplete { _ in
self?.currentClientConnection = nil
}

client.onText { ws, text in
log.debug(text)
}
}
}
}

// MARK: - WebSocketDelegate

extension DVPNServer: WebSocketDelegate {
func send(event: String) {
currentClientConnection?.send(event)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//
// WebSocketDelegate.swift
// SOLARdVPNCommunityCoreiOS
//
// Created by Lika Vorobeva on 04.10.2022.
//

import Foundation

protocol WebSocketDelegate: AnyObject {
func send(event: String)
}

0 comments on commit 699c17c

Please sign in to comment.