[英]Swift Starscream websocket pod not Connecting to local server and no delegate methods called
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. 打印语句“TRYING TO CONNECT”和“DONE TRYING”都出现在日志中,但似乎没有调用任何委托方法。
I am not sure what could be wrong here. 我不确定这里有什么不对。
Any help is appreciated. 任何帮助表示赞赏。
The issue was that, I was creating an instance of the class SocketManager
in the AppDelegate and that variable was falling out of scope. 问题是,我在AppDelegate中创建了一个类
SocketManager
的实例,并且该变量超出了范围。
To solve this, I created an instance variable in the AppDelegate
, after doing that the delegate methods are being called as expected. 为了解决这个问题,我在
AppDelegate
创建了一个实例变量,之后按照预期调用委托方法。
Here's a link to the issue that I posted on their Github repo. 这是我在Github回购中发布的问题的链接。
https://github.com/daltoniam/Starscream/issues/203 https://github.com/daltoniam/Starscream/issues/203
Hope it helps. 希望能帮助到你。
For anyone still confused, the problem (for me) was that I was initialising and calling everything in viewDidLoad
: 对于仍然困惑的人,问题(对我来说)是我在
viewDidLoad
初始化并调用所有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
. 为了解决这个问题,我简单地将
client
定义移动为ViewController
的属性,同时在viewDidLoad
保持connect
和write
。 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!")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.