mirror of https://github.com/vapor/docs.git
websockets docs
This commit is contained in:
parent
e0c0cc8852
commit
e1cdf11950
|
|
@ -140,3 +140,10 @@ menu:
|
|||
http-server:
|
||||
text: Server
|
||||
relativeUrl: http/server.html
|
||||
|
||||
web-sockets:
|
||||
name: WebSockets
|
||||
items:
|
||||
websockets-example:
|
||||
text: Example
|
||||
relativeUrl: websockets/example.html
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
---
|
||||
currentMenu: websockets-example
|
||||
---
|
||||
|
||||
# Using WebSockets
|
||||
|
||||
Below are some examples of WebSockets in use.
|
||||
|
||||
## Client
|
||||
|
||||
```Swift
|
||||
import WebSockets
|
||||
|
||||
try WebSocket.connect(to: url) { ws in
|
||||
print("Connected to \(url)")
|
||||
|
||||
ws.onText = { ws, text in
|
||||
print("[event] - \(text)")
|
||||
}
|
||||
|
||||
ws.onClose = { ws, _, _, _ in
|
||||
print("\n[CLOSED]\n")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Server
|
||||
|
||||
```Swift
|
||||
import HTTP
|
||||
import WebSockets
|
||||
|
||||
final class MyResponder: Responder {
|
||||
func respond(to request: Request) throws -> Response {
|
||||
return try request.upgradeToWebSocket { ws in
|
||||
print("[ws connected]")
|
||||
|
||||
ws.onText = { ws, text in
|
||||
print("[ws text] \(text)")
|
||||
try ws.send("🎙 \(text)")
|
||||
}
|
||||
|
||||
ws.onClose = { _, code, reason, clean in
|
||||
print("[ws close] \(clean ? "clean" : "dirty") \(code?.description ?? "") \(reason ?? "")")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let server = try Server<TCPServerStream, Parser<Request>, Serializer<Response>>(port: port)
|
||||
|
||||
print("Connect websocket to http://localhost:\(port)/")
|
||||
try server.start(responder: MyResponder()) { error in
|
||||
print("Got server error: \(error)")
|
||||
}
|
||||
```
|
||||
Loading…
Reference in New Issue