Vapor文档学习卅五: WEBSOCKETS - Droplet

Droplet WebSockets

使用Droplet创建WebSocket服务器很简单。 WebSockets通过将HTTP请求升级到WebSocket连接来工作。
因此,你应该使用WebSocket服务器驻留的URL。 下面,我们使用 /ws作为案例。

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 {
        while 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)
    }

    ws.onClose = { ws, code, reason, clean in
        print("Closed.")
    }
}

drop.run()

链接 WebSocket的客户端可以通过打开ws:///ws来进行连接。
下面是JavaScript写的客户端方法:

var ws = new WebSocket("ws://0.0.0.0:8080/ws")

ws.onmessage = function(msg) {
    console.log(msg)
}

ws.onopen = function(event) {
    ws.send("test")
}

你可能感兴趣的:(Vapor文档学习卅五: WEBSOCKETS - Droplet)