1

I have been trying to connect to a local server without success. My Code is as follows -

class SocketManager: NSObject, WebSocketDelegate {
    var socket: WebSocket!

    override init() {
        super.init()

        self.socket = WebSocket(url: NSURL(string: "ws://localhost:9292/")!)
        self.socket.delegate = self
        print("TRYING TO CONNECT")
        self.socket.connect()
        print("DONE TRYING")
    }

    func websocketDidConnect(ws: WebSocket) {
        print("websocket is connected")
    }

    func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
         print("websocket is disconnected: \(error?.localizedDescription)")
    }

    func websocketDidReceiveMessage(ws: WebSocket, text: String) {
        print("Received text: \(text)")
    }

    func websocketDidReceiveData(ws: WebSocket, data: NSData) {
         print("Received data: \(data.length)")
    }

    func websocketDidReceivePong(socket: WebSocket) {
        print("Got pong!")
    }
}

Both the Print statements "TRYING TO CONNECT" and "DONE TRYING" are present in the log, but none of the delegate methods seem to be called.

I am not sure what could be wrong here.

Any help is appreciated.

Dwijen
  • 590
  • 4
  • 15

2 Answers2

1

The issue was that, I was creating an instance of the class SocketManager in the AppDelegate and that variable was falling out of scope.

To solve this, I created an instance variable in the AppDelegate, after doing that the delegate methods are being called as expected.

Here's a link to the issue that I posted on their Github repo.

https://github.com/daltoniam/Starscream/issues/203

Hope it helps.

Dwijen
  • 590
  • 4
  • 15
1

For anyone still confused, the problem (for me) was that I was initialising and calling everything in viewDidLoad:

let client = WsClient(echoURL: "ws://localhost:8000/")
client.connect()
client.socket.write(string: "Hi Server!")

To fix this, I simply moved the client definition to be a property of ViewController, while keeping connect and write in viewDidLoad. This worked!

So now I have

class ViewController: UIViewController {
    let client = WsClient(echoURL: "ws://localhost:8000/")
    (...)
    override func viewDidLoad() {
        client.connect()
        client.socket.write(string: "Hi Server!")
    }
}
Felix
  • 428
  • 3
  • 9