Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Vapor を使って VisionPro とWebSocket 通信をしてみる

Vapor を使って VisionPro とWebSocket 通信をしてみる

visionOS勉強会 #7 で発表した資料です。
VaporというWebアプリケーションフレームワークを使って、
WebSocketサーバーを起動し、VisionProから接続してみます

kazuhiro hara

October 23, 2024
Tweet

More Decks by kazuhiro hara

Other Decks in Programming

Transcript

  1. ຊ೔ͷߏ੒ ‣ 7BQPSฤ  7BQPSͱ͸  7BQPSΛ8FC4PDLFUαʔόʔʹ͢Δ ‣ 7JTJPO1SPฤ 

    7JTJPO1SPͰ8FC4PDLFUΛѻ͏ ‣ ·ͱΊ  ਐΊ͍ͯΔϓϩδΣΫτ
  2. ϑΝΠϧߏ੒ . ├── Dockerfile ├── Package.swift ├── Public/ ├── Sources/

    │ └── App/ │ ├── Controllers/ │ ├── configure.swift │ ├── entrypoint.swift │ └── routes.swift ├── Tests/ │ └── AppTests/ │ └── AppTests.swift └── docker-compose.yml
  3. 8FC4PDLFUΛ͔ͭ͏ʹ͸ func routes(_ app: Application) throws { app.get { req

    async in ... } app.get("hello") { req async -> String in ... } app.webSocket("echo") { req, ws in ws.onText { ws, text in print(text) } } } Sources/App/routes.swift
  4. 3PPN؅ཧ class Room { var connections: [String: [WebSocket]] func add(ws:

    WebSocket, room: String) { ... // adding WebSocket to connections } func send(ws: WebSocket, room: String, text: String) { ... // broadcast to connections } init() { connections = [:] } } Sources/App/Room.swift
  5. 3PPNΛͲ͏อ࣋͢Δ͔  ‣ ָͯ͠ ‣ άϩʔόϧม਺ͱ͓ͯ࣋ͬͯ͘͠ͷ͸ඍົͳײ͡  7BQPSͰ(MPCBM4UPSBHFΛߏங͢Δํ๏͕͋Δ w #VJMEJOHBHMPCBMTUPSBHFGPS7BQPSIUUQTUIFTXJGUEFWDPNCVJMEJOHBHMPCBMTUPSBHF

    GPSWBQPS  3FEJTͷ1VC4VCΛར༻͢Δ  w 7BQPSɿ3FEJTˠ0WFSWJFXIUUQTEPDTWBQPSDPEFTSFEJTPWFSWJFX  )VNNJOHCJSEͰ͸ɺϦΫΤετؒͰ৘ใΛ΍ΓͱΓͰ͖Δ࢓૊Έ͕ ͋ΔΒ͍͠ w 1FSTJTUFOUEBUBIUUQTEPDTIVNNJOHCJSEDPEFTEPDVNFOUBUJPOIVNNJOHCJSE QFSTJTUFOUEBUB nonisolated(unsafe) var room = Room()
  6. ίϯιʔϧ͔Β઀ଓͯ͠ΈΔ ‣ ઀ଓ $ npm run start > [email protected] start

    > node src/client.js WebSocket Client Connected Received: '1287346' Received: '4955304' Received: '12177183' Received: '13307824' Received: '16307205' Received: '5869357' Received: '12393997' Received: '7832726'
  7. 8FC4PDLFUʹ઀ଓ͢Δํ๏ ‣ 9DPEFʹͯύοέʔδΛಋೖ͠ɺJNQPSU ‣ ؆୯ͳΞΫηεํ๏ import Starscream ... var request

    = URLRequest(url: URL(string: "http://localhost:8080/echo")!) request.timeoutInterval = 5 socket = WebSocket(request: request) socket.delegate = self socket.connect() ...
  8. 8FC4PDLFU$POUSPMMFSͷ༻ҙ class WebSocketController: WebSocketDelegate, ObservableObject { private var socket: WebSocket!

    @Published var isConnected = false @Published var messages: [String] = [] func didReceive(event: WebSocketEvent, client: WebSocketClient) { ... } init() { connect() } func connect() { ... } func disconnect() { ... } } WebSocketController.swift
  9. $POUFOU7JFX͔Β࢖͏ ‣ 8FC4PDLFU$POUSPMMFS͔ΒૹΒΕͨNFTTBHFΛ औಘ struct ContentView: View { @ObservedObject var

    client = WebSocketController() init() { client = WebSocketController() } var body: some View { VStack { if client.isConnected { List { ForEach(client.messages, id: \.self) { m in Text(m) ...