SocketRocket + Socketio 无法构建握手



我正在尝试根据本教程在iOS应用程序和Socketio服务器之间构建握手:Teehan+Lax

我遇到的问题是连接从未正确打开,我认为这是因为握手+令牌未正确生成:

func initHandshake() {
    let time:NSTimeInterval = NSDate().timeIntervalSince1970 * 1000
    println(time)
    var timeString = "(time)"
    var formattedTime = timeString.stringByReplacingOccurrencesOfString(".", withString: "-", options: NSStringCompareOptions.LiteralSearch)
    println(formattedTime)
    var endpoint = "http://(server)/socket.io/1?t=(formattedTime)"
    println(endpoint)
    var handshakeTask:NSURLSessionTask = session!.dataTaskWithURL(NSURL(fileURLWithPath: endpoint)!, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) in
        if !(error != nil) {
            let stringData:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
            let handshakeToken:NSString = stringData.componentsSeparatedByString(":")[0] as NSString
            println("HANDSHAKE (handshakeToken)")
            self.socketConnect(handshakeToken)
        }
        if ((error) != nil) {
            println("Didn't connect. Why?")
        }
    })
    handshakeTask.resume()
}

您可以看到我在代码中进行了几次尝试,将端点 URL 与 Socketio 返回的字符串匹配,但没有骰子。它仍然无法连接。

我以前没有写过任何 Swift,所以我对这段代码实际上试图抓取的内容感到相当迷茫:

var handshakeTask:NSURLSessionTask = session!.dataTaskWithURL(NSURL(fileURLWithPath: endpoint)!, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) in

有人有什么想法吗?

我最终接受了下面@influxd的建议并使用了SIOSocket。真正帮助我的是很久以前埋藏在这里的问题中的一条评论,一旦我将 SIOSocket 导入我的项目,就可以开始编写代码:

import UIKit
let host = "http://localhost:3000/"
let username = "swiftbot"
let message = "Hello World"
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    self.connectToHost()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
private func connectToHost() {
    SIOSocket.socketWithHost(host, reconnectAutomatically: true, attemptLimit: 0, withDelay: 1, maximumDelay: 5, timeout: 20, response: {socket in
        socket.onConnect = {
            println("Connected to (host)")
            socket.emit("add user", args: [username])
        }
        socket.on("login", callback: {(AnyObject data) -> Void in
            println(["login": data])
            socket.emit("new message", args: [message])
        })
        socket.onDisconnect = {
            println("Disconnected from (host)")
        }
    })
}
}

相关内容

  • 没有找到相关文章

最新更新