swiftwasm / JavaScriptKit

Swift framework to interact with JavaScript through WebAssembly.
https://swiftpackageindex.com/swiftwasm/JavaScriptKit/main/documentation/javascriptkit
MIT License
670 stars 44 forks source link

WebSockets implementation #170

Closed Jomy10 closed 1 year ago

Jomy10 commented 2 years ago

I am trying to open a WebSocket in JavaScriptKit.

I have found a related issue on this, but the implementation did not work for me.

I currently have let socket = JSObject.global.WebSocket.function!. When I print it out, I get a value.

But I don't know how to go from here?

How do I send and receive data with this socket? I've tried some things, but nothing that would compile.

MihaelIsaev commented 1 year ago

@Jomy10 you could take a look at fully working implementation here swifweb/WebSocketAPI

Example usage

import WebSocket

let webSocket = WebSocket("wss://echo.websocket.org").onOpen {
    print("ws connected")
    // send as simple string
    webSocket.send("Hello from SwifWeb")
    // send as Blob
    webSocket.send(Blob("Hello from SwifWeb"))
}.onClose { (closeEvent: CloseEvent) in
    print("ws disconnected code: \(closeEvent.code) reason: \(closeEvent.reason)")
}.onError {
    print("ws error")
}.onMessage { message in
    print("ws message: \(message)")
    switch message.data {
    case .arrayBuffer(let arrayBuffer): break
    case .blob(let blob): break
    case .text(let text): break
    case .unknown(let jsValue): break
    }
}
meqtMac commented 1 year ago

@Jomy10 you could take a look at https://github.com/swiftwasm/WebAPIKit, WebSocket package. I haven't used WebSocket, but WebAPIKit include a great amount of MDB Web API. I have been working with CanvasRenderingContext2D and here is an example

            canvas.element.addEventListener(type: "mousemove") { event in
                if (!running) {
                    let mouseEvent = MouseEvent(unsafelyWrapping: event.jsObject)
                    clear(on: context)
                    ball.x = Double(mouseEvent.clientX);
                    ball.y = Double(mouseEvent.clientY);
                    ball.draw(on: context)
               }
            }

           canvas.element.addEventListener(type: "click") { _ in
                if (!running) {
                    ref = globalThis.requestAnimationFrame { _ in
                        draw(ball: ball, on: context)
                    }
                    running = true
                }
            }

            canvas.element.addEventListener(type: "mouseout") { event in
                guard let ref else { return }
                globalThis.cancelAnimationFrame(handle: ref)
                running = false
            }

            ball.draw(on: canvas.context)

you can also look for MDN's api document and call functions with dynmaic lookup, anyway without IDE autocomplete. By, WebAPIKit, you can call functions with autocomplete just like native swift program with little friction.