我正在尝试根据本教程在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
有人有什么想法吗?
答案 0 :(得分:0)
我最终使用@涌入的建议并使用SIOSocket。真正最终帮助我的是一个很久以前在问题here中埋没的评论,以便在我将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)")
}
})
}
}