Closed dioKaratzas closed 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:
Codable
{ "event": "<event name>" } or { "event": "<event name>", "data": <anything> }
{ "event": "<event name>" }
{ "event": "<event name>", "data": <anything> }
The event data will be decoded to the provided Type.
data
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!
(#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 providedType
.Here is a demo:
The code will become much cleaner as you can give on events a handler!