Starscream icon indicating copy to clipboard operation
Starscream copied to clipboard

WebSocketServer

Open LukeChannings opened this issue 4 years ago • 3 comments

Hello,

I'm trying to get the WebSocketServer implementation to work and it seems to be undocumented. I pieced together the following code, but when I test the connection with a simple let ws = new WebSocket('ws://localhost:27592'), I get an immediate disconnection: "Error during WebSocket handshake: 'Upgrade' header is missing".

import Foundation
import Starscream

class MessageHandler: NSObject {
  var socket: WebSocketServer!

  override init() {
    super.init()
    
    self.socket = WebSocketServer()
    socket.onEvent = { event in
      switch event {
        case .connected(_, let headers):
            print("websocket is connected: \(headers)")
        case .disconnected(_, let reason, let code):
          print("websocket is disconnected: \(reason) with code: \(code)")
        case .text( _, let string):
            print("Received text: \(string)")
        case .binary( _, let data):
            print("Received data: \(data.count)")
        case .ping(_, _):
          break
        case .pong(_, _):
          break
      }
    }
  }
  
  func start() -> Void {
    let error = socket.start(address: "localhost", port: 27592)
    if error != nil {
      print("Error starting web socket server! \(error.debugDescription)")
    }
  }
}

In the app log, however, I get:

websocket is connected: ["Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36", "Origin": "null", "Sec-WebSocket-Key": "LUTOqNlBJh3h0cAjEzTRZg==", "Connection": "Upgrade", "Sec-WebSocket-Version": "13", "Cache-Control": "no-cache", "Accept-Encoding": "gzip, deflate, br", "Upgrade": "websocket", "Host": "localhost:27592", "Pragma": "no-cache", "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"]

And conspicuously no disconnection log. Any ideas?

LukeChannings avatar Apr 26 '20 22:04 LukeChannings

hey @LukeChannings did you get this to work, I also need to start a websocket server inside of my application

ospfranco avatar Jul 03 '20 08:07 ospfranco

Hey @ospfranco. No, I ended up going the Swift-NIO route - https://github.com/apple/swift-nio/blob/master/Sources/NIOWebSocketServer/main.swift

LukeChannings avatar Jul 03 '20 08:07 LukeChannings

oh wow, that is fairly complicated... do you maybe have a snippet for a very simple ws server implementation? I would be really thankful

ospfranco avatar Jul 03 '20 09:07 ospfranco