LoginSignup
3
0

More than 5 years have passed since last update.

VaporでWebSocketを使ったチャットアプリを作る。

Last updated at Posted at 2018-12-06

VaporでももちろんWebSocketを使うことができます。機能が少ないシンプルなので簡単に使うことができます。
今回はVaporでWebSocketを使い、簡単なチャットアプリを作っていきます。
公式 Vapor WebSocket

Vaporのプロジェクトを作成します。

$ vapor new websocketTest
$ cd websocketTest
$ vapor -y xcode  // 必要あれば
$ vapor build
$ vapor run

configure.swiftのプロパティにWebSocketを保持する配列を作成します。

configure.swift
var websocketClients: Dictionary<String, [WebSocket]> = [:]

configure メソッドの中にWebSocketServerの設定を記述していきます。
localhost:8080/socket/xxxx (xxxxはルームの名前) に送られてきた文字列を、同じルームに接続中のクライアントに転送しています。

configure.swift
// WebSockets
let wss = NIOWebSocketServer.default()
wss.get("socket", String.parameter) { ws, req in
    let room = try req.parameters.next(String.self)
    if websocketClients[room] == nil {
        websocketClients[room] = []
    } else {
        websocketClients[room] = websocketClients[room]!.filter({
            !$0.isClosed
        })
    }
    websocketClients[room]!.append(ws)
    ws.onText { ws, text in
        for client in websocketClients[room]! {
            if !client.isClosed {
                if ws === client {
                    print("slip sender")
                } else {
                    client.send(text)
                }
            }
        }
    }
}
services.register(wss, as: WebSocketServer.self)

デバックのために wsta というWebSocketのクライアントを使いました。 
wsta : A CLI development tool for WebSocket APIs

インストール方法

$ brew tap esphen/wsta https://github.com/esphen/wsta.git
$ brew install wsta

サンダースとダグトリオのシェルでkabigon というルームにアクセスします。ダグトリオの方のシェルで送信した文字列がサンダースのシェルに表示されています。

$ wsta ws://localhost:8080/socket/kabigon

websocket.gif

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0