Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hummingbird-project/hummingbird-websocket
Websocket upgrade support for Hummingbird
https://github.com/hummingbird-project/hummingbird-websocket
hummingbird server swift websocket
Last synced: about 1 month ago
JSON representation
Websocket upgrade support for Hummingbird
- Host: GitHub
- URL: https://github.com/hummingbird-project/hummingbird-websocket
- Owner: hummingbird-project
- License: apache-2.0
- Created: 2021-02-13T14:39:27.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-04-30T09:42:32.000Z (8 months ago)
- Last Synced: 2024-05-02T02:53:17.412Z (8 months ago)
- Topics: hummingbird, server, swift, websocket
- Language: Swift
- Homepage:
- Size: 235 KB
- Stars: 23
- Watchers: 5
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Hummingbird Websocket
Adds support for upgrading HTTP1 connections to WebSocket.
## Usage
Setup WebSocket upgrades with a closure that either returns `.upgrade` with response headers and the handler for the WebSocket or a `.dontUpgrade`
```swift
let app = Application(
router: router,
server: .http1WebSocketUpgrade { request, channel, logger in
// upgrade if request URI is "/ws"
guard request.uri == "/ws" else { return .dontUpgrade }
// The upgrade response includes the headers to include in the response and
// the WebSocket handler
return .upgrade([:]) { inbound, outbound, context in
for try await packet in inbound {
// send "Received" for every packet we receive
try await outbound.write(.text("Received"))
}
}
}
)
app.runService()
```
Or alternatively use a `Router`. Using a router means you can add middleware to process the initial upgrade request before it is handled eg for authenticating the request.
```swift
let wsRouter = Router(context: BasicWebSocketRequestContext.self)
wsRouter.middlewares.add(BasicAuthenticator())
// An upgrade only occurs if a WebSocket path is matched
wsRouter.ws("/ws") { request, context in
// allow upgrade
.upgrade()
} onUpgrade: { inbound, outbound, context in
for try await packet in inbound {
// send "Received" for every packet we receive
try await outbound.write(.text("Received"))
}
}
let app = Application(
router: router,
server: .http1WebSocketUpgrade(webSocketRouter: wsRouter)
)
app.runService()
```## Documentation
You can find documentation for HummingbirdWebSocket [here](https://hummingbird-project.github.io/hummingbird-docs/2.0/documentation/hummingbirdwebsocket). The [hummingbird-examples](https://github.com/hummingbird-project/hummingbird-examples) repository has a number of examples of different uses of the library.