Compare commits

..
20 Commits
Author SHA1 Message Date
Erik 16e0bf6319 bump version 2016-02-25 19:13:08 -05:00
Erik Little 11c0ac249b Merge pull request #317 from jtjacka/master
fix timeoutAfter handler always close connection
2016-02-25 19:11:33 -05:00
jtjacka 1e96d7982d fix timeoutAfter handler always close connection 2016-02-25 16:06:08 -08:00
Erik 2f4c942dcf use connect/disconnect for engine 2016-02-23 10:33:14 -05:00
Erik 70283acc1f add messages to deprecated methods 2016-02-17 14:27:48 -05:00
Erik e16914f7d6 remove unused param 2016-02-17 14:15:15 -05:00
Erik c795f9fb25 refactor socketpacket 2016-02-17 14:09:05 -05:00
Erik 12f9207d8a rename waitingData to waitingPackets 2016-02-16 17:03:00 -05:00
Erik 0bf27b8c49 bump version 2016-02-16 14:28:18 -05:00
Erik 6ac96f8d91 modify test 2016-02-16 14:27:18 -05:00
Erik f7397155b6 add test cases 2016-02-16 14:26:21 -05:00
Erik 70d59ea9d4 fix quotes in strings 2016-02-16 14:21:10 -05:00
Erik 7fe2dc2c70 bump version 2016-02-15 10:48:24 -05:00
Erik fe9ee602e7 add option for toggling double encoding utf8 2016-02-15 10:43:21 -05:00
Erik 6fa5ce9168 don't call connect timeout if status is closed 2016-02-14 20:16:01 -05:00
Erik 43b2d4646f bump websocket version 2016-02-12 08:45:44 -05:00
Erik 0f70079382 fix possible race condition 2016-02-11 09:36:36 -05:00
Erik 750ba138e1 bump version 2016-02-05 14:05:50 -05:00
Erik 3e8ca90e3a don't fatalerror 2016-02-05 13:09:26 -05:00
Erik 2a25027077 change to weak self 2016-02-04 15:59:39 -05:00
16 changed files with 256 additions and 249 deletions

No files matched your search

+13 -13
View File
@@ -86,7 +86,7 @@ Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 5.3.2 # Or latest version
github "socketio/socket.io-client-swift" ~> 5.5.0 # Or latest version
```
Run `carthage update --platform ios,macosx`.
@@ -100,7 +100,7 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 5.3.2' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 5.5.0' # Or latest version
```
Install pods:
@@ -128,7 +128,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.3.2", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v5.5.0", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
@@ -147,24 +147,24 @@ All options are a case of SocketIOClientOption. To get the Objective-C Option, c
```swift
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case DoubleEncodeUTF8(Bool) // Whether or not to double encode utf8. If using the node based server this should be true. Default is true.
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case Log(Bool) // If `true` socket will log debug messages. Default is false.
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Path(String) // If the server uses a custom path. ex: `"/swift/"`. Default is `""`
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
case Reconnects(Bool) // Whether to reconnect on server lose. Default is `true`
case ReconnectAttempts(Int) // How many times to reconnect. Default is `-1` (infinite tries)
case ReconnectWait(Int) // Amount of time to wait between reconnects. Default is `10`
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case Secure(Bool) // If the connection should use TLS. Default is false.
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
```
Methods
-------
+2 -2
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIOClientSwift"
s.version = "5.3.2"
s.version = "5.5.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.3.2' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.5.0' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
@@ -60,11 +60,6 @@
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E581C10CD240062D398 /* SocketFixUTF8.swift */; };
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9A1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
@@ -180,7 +175,6 @@
74171E551C10CD240062D398 /* SocketEnginePacketType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEnginePacketType.swift; path = Source/SocketEnginePacketType.swift; sourceTree = "<group>"; };
74171E561C10CD240062D398 /* SocketEngineSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEngineSpec.swift; path = Source/SocketEngineSpec.swift; sourceTree = "<group>"; };
74171E571C10CD240062D398 /* SocketEventHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketEventHandler.swift; path = Source/SocketEventHandler.swift; sourceTree = "<group>"; };
74171E581C10CD240062D398 /* SocketFixUTF8.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketFixUTF8.swift; path = Source/SocketFixUTF8.swift; sourceTree = "<group>"; };
74171E591C10CD240062D398 /* SocketIOClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClient.swift; path = Source/SocketIOClient.swift; sourceTree = "<group>"; };
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientOption.swift; path = Source/SocketIOClientOption.swift; sourceTree = "<group>"; };
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientStatus.swift; path = Source/SocketIOClientStatus.swift; sourceTree = "<group>"; };
@@ -361,7 +355,6 @@
74171E561C10CD240062D398 /* SocketEngineSpec.swift */,
740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */,
74171E571C10CD240062D398 /* SocketEventHandler.swift */,
74171E581C10CD240062D398 /* SocketFixUTF8.swift */,
74171E591C10CD240062D398 /* SocketIOClient.swift */,
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */,
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */,
@@ -610,7 +603,6 @@
buildActionMask = 2147483647;
files = (
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */,
74171E931C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */,
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */,
@@ -647,7 +639,6 @@
74171EC41C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E941C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171ECA1C10CD240062D398 /* SwiftRegex.swift in Sources */,
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */,
@@ -670,7 +661,6 @@
files = (
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEA1C39926300364B59 /* SocketClientSpec.swift in Sources */,
74171E951C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
@@ -713,7 +703,6 @@
files = (
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEB1C39926C00364B59 /* SocketClientSpec.swift in Sources */,
74171E971C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
@@ -749,7 +738,6 @@
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E981C10CD240062D398 /* SocketFixUTF8.swift in Sources */,
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171ECE1C10CD240062D398 /* SwiftRegex.swift in Sources */,
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */,
@@ -37,6 +37,14 @@ class SocketBasicPacketTest: XCTestCase {
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmitWithQuotes() {
let expectedSendString = "2[\"test\",\"\\\"he\\\"llo world\\\"\"]"
let sendData = ["test", "\"he\"llo world\""]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
@@ -70,6 +70,17 @@ class SocketSideEffectTest: XCTestCase {
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleOnceEvent() {
let expectation = expectationWithDescription("handled event")
socket.once("test") {data, ack in
+1 -1
View File
@@ -24,7 +24,7 @@
protocol SocketClientSpec: class {
var nsp: String { get set }
var waitingData: [SocketPacket] { get set }
var waitingPackets: [SocketPacket] { get set }
func didConnect()
func didDisconnect(reason: String)
+76 -62
View File
@@ -41,6 +41,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var doubleEncodeUTF8 = true
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
public private(set) var forcePolling = false
@@ -88,18 +89,20 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
switch option {
case let .ConnectParams(params):
connectParams = params
case let .Cookies(cookies):
self.cookies = cookies
case let .DoubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .SessionDelegate(delegate):
sessionDelegate = delegate
case let .ForcePolling(force):
forcePolling = force
case let .ForceWebsockets(force):
forceWebsockets = force
case let .Cookies(cookies):
self.cookies = cookies
case let .Path(path):
socketPath = path
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .VoipEnabled(enable):
voipEnabled = enable
case let .Secure(secure):
@@ -120,13 +123,13 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
}
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(client: SocketEngineClient, urlString: String, options: Set<SocketIOClientOption>) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options)
}
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) {
guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") }
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
@@ -183,29 +186,42 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
public func close(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
disconnect(reason)
}
/// Starts the connection to the server
public func connect() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
close("reconnect")
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = createRequestForPostWithPostWait()
doRequest(req, withCallback: postSendClose)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
private func createURLs() -> (NSURL, NSURL) {
@@ -271,6 +287,35 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
client?.engineDidError(error)
close(error)
}
public func disconnect(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(req, withCallback: postSendClose)
}
}
}
public func doFastUpgrade() {
if waitingForPoll {
@@ -377,37 +422,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
public func open() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
close("reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
connect()
}
public func parseEngineData(data: NSData) {
@@ -429,7 +444,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
return
}
if fromPolling && type != .Noop {
if fromPolling && type != .Noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
@@ -451,6 +466,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
connected = false
@@ -479,12 +495,11 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
write("", withType: .Ping, withData: [])
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
@@ -492,6 +507,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
@@ -502,9 +518,7 @@ public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWeb
}
}
/**
Write a message, independent of transport.
*/
/// Write a message, independent of transport.
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
dispatch_async(emitQueue) {
guard self.connected else { return }
+21 -14
View File
@@ -206,21 +206,28 @@ extension SocketEnginePollable {
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage = doubleEncodeUTF8(message)
let strMsg = "\(type.rawValue)\(fixedMessage)"
postWait.append(strMsg)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage: String
if doubleEncodeUTF8 {
fixedMessage = doubleEncodeUTF8(message)
} else {
fixedMessage = message
}
let strMsg = "\(type.rawValue)\(fixedMessage)"
postWait.append(strMsg)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
public func stopPolling() {
+23 -2
View File
@@ -30,6 +30,7 @@ import Foundation
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: AnyObject]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
@@ -49,11 +50,13 @@ import Foundation
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
func close(reason: String)
@available(*, deprecated=5.5, message="Please use disconnect") func close(reason: String)
func connect()
func didError(error: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func open()
@available(*, deprecated=5.5, message="Please use connect") func open()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
@@ -89,6 +92,24 @@ extension SocketEngineSpec {
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
/// Send an engine message (4)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
-44
View File
@@ -1,44 +0,0 @@
//
// SocketFixUTF8.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/16/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
+19 -26
View File
@@ -53,7 +53,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
var waitingPackets = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
@@ -102,15 +102,13 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(socketURLString: String, options: Set<SocketIOClientOption> = []) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options)
}
/// Please use the NSURL based init
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use the NSURL based init")
public convenience init(socketURLString: String, options: NSDictionary?) {
guard let url = NSURL(string: socketURLString) else { fatalError("Incorrect url") }
self.init(socketURL: url, options: options?.toSocketOptionsSet() ?? [])
@@ -118,7 +116,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.close("Client Deinit")
engine?.disconnect("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
@@ -134,7 +132,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
reconnectTimer = nil
}
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use disconnect()")
public func close() {
disconnect()
}
@@ -161,19 +159,19 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
status = .Connecting
if engine == nil || forceNew {
addEngine().open()
addEngine().connect()
} else {
engine?.open()
engine?.connect()
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
if let this = self where this.status != .Connected && this.status != .Closed {
this.status = .Closed
this.engine?.close("Connect timeout")
this.engine?.disconnect("Connect timeout")
handler?()
}
@@ -214,9 +212,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
guard status != .Closed else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
@@ -224,7 +220,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
reconnects = false
// Make sure the engine is actually dead.
engine?.close(reason)
engine?.disconnect(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
@@ -254,9 +250,9 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
self._emit([event] + items)
dispatch_async(emitQueue) {[emitData = [event] + items] in
self._emit(emitData)
}
}
@@ -280,10 +276,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
@@ -304,7 +300,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
waitingPackets.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
@@ -428,10 +424,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketParsable
anyHandler = handler
}
/**
Same as connect
*/
@available(*, deprecated=5.3)
@available(*, deprecated=5.3, message="Please use one of the connect methods)")
public func open() {
connect()
}
+26 -19
View File
@@ -31,6 +31,7 @@ protocol ClientOption: CustomStringConvertible, Hashable {
public enum SocketIOClientOption: ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
@@ -56,6 +57,8 @@ public enum SocketIOClientOption: ClientOption {
description = "connectParams"
case .Cookies:
description = "cookies"
case .DoubleEncodeUTF8:
description = "doubleEncodeUTF8"
case .ExtraHeaders:
description = "extraHeaders"
case .ForceNew:
@@ -105,6 +108,8 @@ public enum SocketIOClientOption: ClientOption {
value = params
case let .Cookies(cookies):
value = cookies
case let .DoubleEncodeUTF8(encode):
value = encode
case let .ExtraHeaders(headers):
value = headers
case let .ForceNew(force):
@@ -156,44 +161,46 @@ extension Set where Element: ClientOption {
}
extension NSDictionary {
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
case let ("reconnects", reconnects as Bool):
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .ReconnectWait(wait)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("doubleEncodeUTF8", encode as Bool):
return .DoubleEncodeUTF8(encode)
case let ("extraHeaders", headers as [String: String]):
return .ExtraHeaders(headers)
case let ("forceNew", force as Bool):
return .ForceNew(force)
case let ("forcePolling", force as Bool):
return .ForcePolling(force)
case let ("forceWebsockets", force as Bool):
return .ForceWebsockets(force)
case let ("nsp", nsp as String):
return .Nsp(nsp)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("log", log as Bool):
return .Log(log)
case let ("logger", logger as SocketLogger):
return .Logger(logger)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("nsp", nsp as String):
return .Nsp(nsp)
case let ("path", path as String):
return .Path(path)
case let ("extraHeaders", headers as [String: String]):
return .ExtraHeaders(headers)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("voipEnabled", enable as Bool):
return .VoipEnabled(enable)
case let ("reconnects", reconnects as Bool):
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .ReconnectWait(wait)
case let ("secure", secure as Bool):
return .Secure(secure)
case let ("selfSigned", selfSigned as Bool):
return .SelfSigned(selfSigned)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("voipEnabled", enable as Bool):
return .VoipEnabled(enable)
default:
return nil
}
+30 -40
View File
@@ -86,39 +86,29 @@ struct SocketPacket {
}
}
private func completeMessage(message: String, ack: Bool) -> String {
var restOfMessage = ""
private func completeMessage(message: String) -> String {
let restOfMessage: String
if data.count == 0 {
return message + "]"
return message + "[]"
}
for arg in data {
if arg is NSDictionary || arg is [AnyObject] {
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(rawValue: 0))
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
restOfMessage += jsonString! + ","
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
}
} else if let str = arg as? String {
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
} else if arg is NSNull {
restOfMessage += "null,"
} else {
restOfMessage += "\(arg),"
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
options: NSJSONWritingOptions(rawValue: 0))
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
return "[]"
}
restOfMessage = jsonString
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
restOfMessage = "[]"
}
if restOfMessage != "" {
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
}
return message + restOfMessage + "]"
return message + restOfMessage
}
private func createAck() -> String {
@@ -126,19 +116,19 @@ struct SocketPacket {
if type == .Ack {
if nsp == "/" {
message = "3\(id)["
message = "3\(id)"
} else {
message = "3\(nsp),\(id)["
message = "3\(nsp),\(id)"
}
} else {
if nsp == "/" {
message = "6\(binary.count)-\(id)["
message = "6\(binary.count)-\(id)"
} else {
message = "6\(binary.count)-\(nsp),\(id)["
message = "6\(binary.count)-\(nsp),\(id)"
}
}
return completeMessage(message, ack: true)
return completeMessage(message)
}
@@ -148,34 +138,34 @@ struct SocketPacket {
if type == .Event {
if nsp == "/" {
if id == -1 {
message = "2["
message = "2"
} else {
message = "2\(id)["
message = "2\(id)"
}
} else {
if id == -1 {
message = "2\(nsp),["
message = "2\(nsp),"
} else {
message = "2\(nsp),\(id)["
message = "2\(nsp),\(id)"
}
}
} else {
if nsp == "/" {
if id == -1 {
message = "5\(binary.count)-["
message = "5\(binary.count)-"
} else {
message = "5\(binary.count)-\(id)["
message = "5\(binary.count)-\(id)"
}
} else {
if id == -1 {
message = "5\(binary.count)-\(nsp),["
message = "5\(binary.count)-\(nsp),"
} else {
message = "5\(binary.count)-\(nsp),\(id)["
message = "5\(binary.count)-\(nsp),\(id)"
}
}
}
return completeMessage(message, ack: false)
return completeMessage(message)
}
private func createPacketString() -> String {
+5 -5
View File
@@ -50,9 +50,9 @@ extension SocketParsable {
case .Ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
waitingPackets.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
@@ -160,17 +160,17 @@ extension SocketParsable {
}
func parseBinaryData(data: NSData) {
guard !waitingData.isEmpty else {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingData[waitingData.count - 1].addData(data) else {
guard waitingPackets[waitingPackets.count - 1].addData(data) else {
return
}
let packet = waitingData.removeLast()
let packet = waitingPackets.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
+14 -3
View File
@@ -19,15 +19,26 @@ private let lock = dispatch_semaphore_create(1)
private var swiftRegexCache = [String: NSRegularExpression]()
internal final class SwiftRegex: NSObject, BooleanType {
var target:String
var target: String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
self.target = target
if dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, Int64(10 * NSEC_PER_MSEC))) != 0 {
fatalError("This should never happen")
do {
let regex = try NSRegularExpression(pattern: pattern, options:
NSRegularExpressionOptions.DotMatchesLineSeparators)
self.regex = regex
} catch let error as NSError {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
super.init()
return
}
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
+7 -6
View File
@@ -308,13 +308,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
let bytes = UnsafePointer<UInt8>(data.bytes)
var timeout = 5000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [unowned self] in
writeQueue.addOperationWithBlock { [weak self] in
guard let this = self else { return }
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
timeout -= 100
if timeout < 0 {
self.cleanupStream()
self.doDisconnect(self.errorWithDetail("write wait timed out", code: 2))
this.cleanupStream()
this.doDisconnect(this.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
@@ -436,7 +437,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k++
k += 1
if k == 3 {
totalSize = i + 1
break
@@ -659,7 +660,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount++
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
@@ -957,7 +958,7 @@ private class SSLSecurity {
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
trustedCount += 1
break
}
}