1

I have been facing Ann issue with Websocket to connection, I have tried several methods to get connected, but always showing connection refused or failed connection. The library I have using is Starscream ref:- https://github.com/daltoniam/Starscream and also tried with RxStarscream ref:- https://github.com/RxSwiftCommunity/RxStarscream.

In both cases when I tried the following code,

@_exported import RxSwift
@_exported import RxStarscream
import Starscream

  override func viewDidLoad() {
        super.viewDidLoad()
 private let disposeBag = DisposeBag()
 
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!)
        socket.connect()

 socket.rx.response.subscribe(onNext: { (response: WebSocketEvent) in
            switch response {
            case .connected:
                print("Connected")
            case .disconnected(let error):
                print("Disconnected with optional error : \(error)")
            case .message(let msg):
                print("Message : \(msg)")
            case .data(_):
                print("Data")
            case .pong:
                print("Pong")
            }
        }).disposed(by: disposeBag)
}

I am beginner in web socket, what am trying to configure is I need to connect the websocket and socket event need to call, followed by target

Socket Events
URI : ws://{host}:{port}?token={_token}&lang={en}
Ip = {dev,qc}.example-app.info
Port = 8090
Main structure for Events Request and Response
{
event:”Event Name”
data:”Event Data”,
is_player:boolean(true,false)
}
Example: {"event":"xxxx","data":"xxxx", "is_player":true}

If anyone could give an idea or just suggestion on how to implement on the above web socket method for iOS with swift will be appreciated.

Aleesha
  • 124
  • 2
  • 21
  • If you declare the `disposeBag` in viewDidLoad it will be deallocated as soon as the viewDidLoad execution completes. This means that your subscription will also get disposed. You should have the disposeBag as a property of the ViewController. – Fabio Felici Nov 13 '20 at 09:24
  • Just noticed that you are using `private let` in the disposeBag declaration and that should throw a compiler error if you do that in viewDidLoad. Are you sure your copied your code correctly? – Fabio Felici Nov 13 '20 at 09:27

1 Answers1

1

Move your private let disposeBag = DisposeBag() to the outside of the viewDidLoad. Because the way you've done it, your subscription dies as soon as your viewDidLoad finishes executing.

Rukshan
  • 7,902
  • 6
  • 43
  • 61