Compare commits

...
11 Commits
Author SHA1 Message Date
Erik 58571e5387 bump version 2015-06-07 13:15:03 -04:00
Erik 1a54decd51 fix socketio/socket.io-client-swift#93 2015-06-06 22:30:56 -04:00
Erik d982cdc1b2 only do interpolation when logging 2015-06-06 13:15:22 -04:00
Erik 079063e396 bump version 2015-06-05 06:59:20 -04:00
Erik 33d5fd3f10 fix base64 data 2015-06-05 06:57:59 -04:00
Erik 3be5621263 remove comment 2015-05-31 11:09:25 -04:00
Erik 81ab71f519 extract methods 2015-05-31 11:07:48 -04:00
Erik bfeec57c04 don't need type 2015-05-29 10:30:59 -04:00
Erik 0b09a1357c use didset instead of computed variable 2015-05-29 10:29:26 -04:00
Erik e8dfe589ac redo pingtimeouts 2015-05-29 10:10:24 -04:00
Erik fcebc870c3 fix socket.io/socket.io-client-swift#87 2015-05-27 07:28:06 -04:00
5 changed files with 134 additions and 74 deletions

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "2.3.2"
s.version = "2.3.4"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -12,7 +12,7 @@ Pod::Spec.new do |s|
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.3.2' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.3.4' }
s.source_files = "SocketIOClientSwift/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
+92 -52
View File
@@ -40,7 +40,15 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingInterval:Int?
private var pingTimer:NSTimer?
private var pingTimeout = 0 {
didSet {
pongsMissedMax = pingTimeout / (pingInterval ?? 25)
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var _polling = true
private var probing = false
@@ -58,7 +66,6 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var log = false
var pingInterval:Int?
var polling:Bool {
return _polling
}
@@ -109,7 +116,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
public func close(#fast:Bool) {
SocketLogger.log("Engine is being closed. Fast: \(fast)", client: self)
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
pingTimer?.invalidate()
closed = true
@@ -213,7 +220,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
if websocket || waitingForPoll || !connected {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!)
@@ -317,7 +324,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
waitingForPost = true
SocketLogger.log("POSTing: \(postStr)", client: self)
SocketLogger.log("POSTing: %@", client: self, args: postStr)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
@@ -350,13 +357,46 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
postWait.removeAll(keepCapacity: true)
}
private func handleClose() {
if polling {
client?.engineDidClose("Disconnect")
}
}
private func checkIfMessageIsBase64Binary(var message:String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters), client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
private func handleMessage(message:String) {
if let client = client {
dispatch_async(client.handleQueue) {[weak client] in
client?.parseSocketMessage(message)
}
}
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData:String) {
var err:NSError?
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments,
error: &err) as? NSDictionary, let sid = json["sid"] as? String {
error: &err) as? NSDictionary, sid = json["sid"] as? String {
self.sid = sid
_connected = true
@@ -364,8 +404,9 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
createWebsocket(andConnect: true)
}
if let pingInterval = json["pingInterval"] as? Int {
if let pingInterval = json["pingInterval"] as? Int, pingTimeout = json["pingTimeout"] as? Int {
self.pingInterval = pingInterval / 1000
self.pingTimeout = pingTimeout / 1000
}
} else {
client?.didError("Engine failed to handshake")
@@ -379,6 +420,15 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
}
private func handlePong(pongMessage:String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
_connected = false
@@ -459,19 +509,16 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
length += chr
} else {
if length == "" || testLength(length, &n) {
SocketLogger.err("Parsing error: \(str)", client: self)
SocketLogger.err("Parsing error: %@", client: self, args: str)
handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i+1...i+n])
if let lengthInt = length.toInt() {
if lengthInt != count(msg) {
SocketLogger.err("parsing error: \(str)", client: self)
return
}
if let lengthInt = length.toInt() where lengthInt != count(msg) {
SocketLogger.err("Parsing error: %@", client: self, args: str)
return
}
if count(msg) != 0 {
@@ -496,49 +543,32 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
SocketLogger.log("Got message: \(message)", client: self)
SocketLogger.log("Got message: %@", client: self, args: message)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1]))
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
self.checkIfMessageIsBase64Binary(message)
return PacketType.NOOP
}()
if type == PacketType.MESSAGE {
// Remove message type
switch type {
case PacketType.MESSAGE:
message.removeAtIndex(message.startIndex)
if let client = client {
dispatch_async(client.handleQueue) {[weak client] in
client?.parseSocketMessage(message)
}
}
} else if type == PacketType.NOOP {
doPoll()
} else if type == PacketType.PONG {
// We should upgrade
if message == "3probe" {
upgradeTransport()
}
} else if type == PacketType.OPEN {
handleMessage(message)
case PacketType.NOOP:
handleNOOP()
case PacketType.PONG:
handlePong(message)
case PacketType.OPEN:
message.removeAtIndex(message.startIndex)
handleOpen(message)
} else if type == PacketType.CLOSE {
if polling {
client?.engineDidClose("Disconnect")
}
} else if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters), client = client {
dispatch_async(client.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
case PacketType.CLOSE:
handleClose()
default:
SocketLogger.log("Got unknown packet type", client: self)
}
}
@@ -557,7 +587,15 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
}
}
func sendPing() {
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: PacketType.PING, withData: nil)
}
@@ -565,7 +603,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending poll: \(msg) as type: \(type.rawValue)", client: self)
SocketLogger.log("Sending poll: %@ as type: %@", client: self, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
@@ -589,7 +627,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending ws: \(str) as type: \(type.rawValue)", client: self)
SocketLogger.log("Sending ws: %@ as type: %@", client: self, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
@@ -640,10 +678,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
dispatch_async(emitQueue) {[weak self] in
if let this = self where this.connected {
if this.websocket {
SocketLogger.log("Writing ws: \(msg):\(data)", client: this)
SocketLogger.log("Writing ws: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
SocketLogger.log("Writing poll: \(msg):\(data)", client: this)
SocketLogger.log("Writing poll: %@ has data: %@", client: this,
args: msg, data == nil ? false : true)
this.sendPollMessage(msg, withType: type, datas: data)
}
}
+14 -11
View File
@@ -131,6 +131,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
deinit {
SocketLogger.log("Client is being deinit", client: self)
engine?.close(fast: true)
}
private func addEngine() {
@@ -235,7 +236,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
return
}
SocketLogger.log("Disconnected: \(reason)", client: self)
SocketLogger.log("Disconnected: %@", client: self, args: reason)
_closed = true
_connected = false
@@ -250,7 +251,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
/// error
public func didError(reason:AnyObject) {
SocketLogger.err("Error: \(reason)", client: self)
SocketLogger.err("%@", client: self, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
@@ -323,7 +324,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
SocketParser.parseForEmit(packet)
str = packet.createMessageForEvent(event)
SocketLogger.log("Emitting: \(str)", client: self)
SocketLogger.log("Emitting: %@", client: self, args: str)
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
engine?.send(str, withData: packet.binary)
@@ -342,7 +343,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
SocketParser.parseForEmit(packet)
str = packet.createAck()
SocketLogger.log("Emitting Ack: \(str)", client: this)
SocketLogger.log("Emitting Ack: %@", client: this, args: str)
if packet.type == SocketPacket.PacketType.BINARY_ACK {
this.engine?.send(str, withData: packet.binary)
@@ -359,7 +360,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
_connecting = false
if closed || !reconnects {
didDisconnect("Engine closed")
didDisconnect(reason)
} else if !reconnecting {
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
@@ -368,7 +369,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
// Called when the socket gets an ack for something it sent
func handleAck(ack:Int, data:AnyObject?) {
SocketLogger.log("Handling ack: \(ack) with data: \(data)", client: self)
SocketLogger.log("Handling ack: %@ with data: %@", client: self,
args: ack, data ?? "")
ackHandlers.executeAck(ack,
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
@@ -384,7 +386,8 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
return
}
SocketLogger.log("Handling event: \(event) with data: \(data)", client: self)
SocketLogger.log("Handling event: %@ with data: %@", client: self,
args: event, data ?? "")
if anyHandler != nil {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
@@ -428,7 +431,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
Removes handler(s)
*/
public func off(event:String) {
SocketLogger.log("Removing handler for event: \(event)", client: self)
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
handlers = handlers.filter {$0.event == event ? false : true}
}
@@ -436,10 +439,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
/**
Adds a handler for an event.
*/
public func on(name:String, callback:NormalCallback) {
SocketLogger.log("Adding handler for event: \(name)", client: self)
public func on(event:String, callback:NormalCallback) {
SocketLogger.log("Adding handler for event: %@", client: self, args: event)
let handler = SocketEventHandler(event: name, callback: callback)
let handler = SocketEventHandler(event: event, callback: callback)
handlers.append(handler)
}
+24 -4
View File
@@ -24,6 +24,8 @@
import Foundation
private let MESSAGE_LENGTH_MAX = 10000
protocol SocketLogClient {
var log:Bool {get set}
var logType:String {get}
@@ -32,23 +34,41 @@ protocol SocketLogClient {
final class SocketLogger {
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
static func log(message:String, client:SocketLogClient, altType:String? = nil) {
private static func shorten(item:AnyObject) -> CVarArgType {
var str = toString(item)
if count(str) > MESSAGE_LENGTH_MAX {
let endIndex = advance(str.startIndex, MESSAGE_LENGTH_MAX)
str = str.substringToIndex(endIndex)
}
return str
}
static func log(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
if !client.log {
return
}
dispatch_async(printQueue) {[type = client.logType] in
NSLog("%@: %@", altType ?? type, message)
let newArgs = args.map(SocketLogger.shorten)
let replaced = String(format: message, arguments: newArgs)
NSLog("%@: %@", altType ?? type, replaced)
}
}
static func err(message:String, client:SocketLogClient, altType:String? = nil) {
static func err(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
if !client.log {
return
}
dispatch_async(printQueue) {[type = client.logType] in
NSLog("ERROR %@: %@", altType ?? type, message)
let newArgs = args.map(SocketLogger.shorten)
let replaced = String(format: message, arguments: newArgs)
NSLog("ERROR %@: %@", altType ?? type, replaced)
}
}
}
+2 -5
View File
@@ -185,7 +185,7 @@ class SocketParser {
return nsp == "" && socket.nsp != "/"
}
SocketLogger.log("Parsing \(stringMessage)", client: socket, altType: "SocketParser")
SocketLogger.log("Parsing %@", client: socket, altType: "SocketParser", args: stringMessage)
let p:SocketPacket
@@ -196,10 +196,7 @@ class SocketParser {
return
}
// Don't call SocketPacket.description unless we need to
if socket.log {
SocketLogger.log("Decoded packet as: \(p)", client: socket, altType: "SocketParser")
}
SocketLogger.log("Decoded packet as: %@", client: socket, altType: "SocketParser", args: p)
if p.type == SocketPacket.PacketType.EVENT {
if checkNSP(p.nsp) {