websockets docs

This commit is contained in:
Tanner Nelson 2016-11-03 13:44:09 -04:00
parent e0c0cc8852
commit e1cdf11950
No known key found for this signature in database
GPG Key ID: 9C24375C64856B76
2 changed files with 63 additions and 0 deletions

View File

@ -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

56
websockets/example.md Normal file
View File

@ -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)")
}
```