From 4e70890a19cb65ce14ff5d70b1496982aba251ca Mon Sep 17 00:00:00 2001 From: Tanner Nelson Date: Thu, 3 Nov 2016 14:20:10 -0400 Subject: [PATCH] web socket update --- websockets/example.md | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/websockets/example.md b/websockets/example.md index 77dd8cd6..0ebf0780 100644 --- a/websockets/example.md +++ b/websockets/example.md @@ -6,6 +6,61 @@ currentMenu: websockets-example Below are some examples of WebSockets in use. +## Droplet + +Creating a WebSocket server with the Droplet is easy. WebSockets work by upgrading an HTTP request to a WebSocket connection. + +Because of this, you should pick a URL for your WebSocket server to reside at. In this case, we use `/ws`. + +```swift +import Vapor + +let drop = Droplet() + +drop.socket("ws") { req, ws in + print("New WebSocket connected: \(ws)") + + // ping the socket to keep it open + try background { + if ws.state == .open { + try? ws.ping() + drop.console.wait(seconds: 10) // every 10 seconds + } + } + + ws.onText = { ws, text in + print("Text received: \(text)") + + // reverse the characters and send back + let rev = String(text.characters.reversed()) + try ws.send(rev.bytes) + } + + ws.onClose = { ws, code, reason, clean in + print("Closed.") + } +} + +drop.run() +``` + +To connect with a WebSocket client, you would open a connection to `ws:///ws`. + +Here is an example using JavaScript. + +```js + +var ws = new WebSocket("ws://0.0.0.0:8080/ws") + +ws.onmessage = function(msg) { + console.log(msg) +} + +ws.send('test') +``` + +The above will log `tset` (`test` reversed). + ## Client ```Swift