Hi! I'm about to try and get started with a small little WebSocket client. I see that Vapor currently has a WebSocket client with this API to receive messages:[1]
ws.onText { ws, text in
// String received by this WebSocket.
print(text)
}
ws.onBinary { ws, binary in
// [UInt8] received by this WebSocket.
print(binary)
}
I was kind of thinking it might be possible to listen for WebSocket messages using AsyncSequence:[2]
for await (ws, text) in ws.onText {
// String received by this WebSocket.
print(text)
}
for await (ws, binary) in ws.onBinary {
// [UInt8] received by this WebSocket.
print(binary)
}
I guess I could try building that myself. Did anyone have an open-source solution that already does this? Thanks!
Keep in mind that would mean you need to put those inside a task -
Task {
for await (ws, text) in ws.onText {
// String received by this WebSocket.
print(text)
}
}
Task {
for await (ws, binary) in ws.onBinary {
// [UInt8] received by this WebSocket.
print(binary)
}
}
Might be less boilerplate to just do the callbacks.
But if you still wanted async streams could do something along the lines of...
let channel = AsyncChannel<[UInt8]>()
ws.onBinary { _, binary in
await channel.send(binary)
}
// elswhere
Task {
for try await binary in channel {
// handle
}
}