vapor / websocket-kit

WebSocket client library built on SwiftNIO
https://docs.vapor.codes/4.0/advanced/websockets/
MIT License
272 stars 79 forks source link

Support Codable Messages #103

Closed dioKaratzas closed 2 years ago

dioKaratzas commented 2 years ago

(#103, fixes #62).

Many Thanks to @MihaelIsaev for the inspiration!

Those changes adds support to send Codable messages and receive events in special JSON format:

{ "event": "<event name>" } or { "event": "<event name>", "data": <anything> }

The event data will be decoded to the provided Type.

Here is a demo:

struct WebSocketController: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        routes.webSocket("chat") { req, ws in
            ws.onEvent("hello", helloHandler)

            ws.onEvent("bye", Bye.self) { ws, data in
                print("Bye \(data.firstName) \(data.lastName)")
                ws.send(Response(status: "Bye bye!"))
            }

            ws.onText { ws, text in
                print(text)
            }

            ws.onEvent("stop") { ws in
                // stop event without data
            }

            ws.onEvent("start", startHandler)
        }
    }
}

// MARK: - WebSocket Event Handlers
extension WebSocketController {
    func helloHandler(webSocket: WebSocket, data: Hello) {
        print("Hello \(data.firstName) \(data.lastName)")
        webSocket.send(Response(status: "Hey There \(data.firstName) \(data.lastName)"), type: .binary)
    }

    func startHandler(webSocket: WebSocket) {
        // start event
    }
}

// MARK: - Codables
struct Hello: Codable {
    let firstName, lastName: String
}

struct Bye: Codable {
    let firstName, lastName: String
}

struct Response: Codable {
    let status: String
}

The code will become much cleaner as you can give on events a handler!