0

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

我遇到的问题是连接永远不会正确打开,我认为这是因为 Handshake + 令牌没有正确生成:

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

有人有想法么?

4

1 回答 1

0

我最终接受了@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)")
        }
    })
}
}
于 2015-01-28T21:39:44.217 回答