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://<ip>/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")
}
网友评论