美文网首页
Vapor文档学习卅六: WEBSOCKETS - Custom

Vapor文档学习卅六: WEBSOCKETS - Custom

作者: Supremodeamor | 来源:发表于2017-04-25 09:51 被阅读54次

    Custom WebSocket

    下面是一个完整的使用WebSockets底层引擎包的实例。

    Client

    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

    import HTTP
    import WebSockets
    import Transport
    
    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 port = 8080
    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)")
    }
    

    相关文章

      网友评论

          本文标题:Vapor文档学习卅六: WEBSOCKETS - Custom

          本文链接:https://www.haomeiwen.com/subject/sdomzttx.html