Compare commits

...
209 Commits
Author SHA1 Message Date
Erik 1949b1fd48 actually bump version 2017-03-30 18:58:26 -04:00
Erik 6bf970e491 bump version 2017-03-30 18:54:04 -04:00
Erik 23050890e9 Merge branch 'development'
* development:
  Revert "double encoding should be getting fixed, make the default false"
2017-03-30 18:53:11 -04:00
Erik d3c1d0cd04 Revert "double encoding should be getting fixed, make the default false"
This reverts commit 0fcb7903bb.
2017-03-30 18:52:42 -04:00
Erik 3faf183cb2 bump version 2017-03-29 12:22:15 -04:00
Erik fafd8b5f22 Merge branch 'development'
* development:
  bump websocket
  note that swift2.3 is a tag now
  Bump websocket version, fix some warnings
2017-03-29 12:20:37 -04:00
Erik 373c1a3447 bump websocket 2017-03-29 12:20:28 -04:00
Erik 3d5cf24de4 note that swift2.3 is a tag now 2017-03-28 05:14:39 -04:00
Erik 1f8c8b8f61 note that swift2.3 is a tag now 2017-03-28 05:14:25 -04:00
Erik 9e94ed1cea Bump websocket version, fix some warnings 2017-03-28 05:10:46 -04:00
Erik 01790af3c5 bump version for xcode 8.3 2017-03-28 05:03:14 -04:00
Erik 551ad7f6af bump version 2017-03-08 19:56:48 -05:00
Erik b3fd4203d2 Merge branch 'development'
* development:
  SocketAckManager thread-safe acks removal
  thread-safe ack generation
  bump websocket
  Fix building on xcode8.3
  double encoding should be getting fixed, make the default false
  bump websocket
2017-03-08 19:55:46 -05:00
Erik Little c462381587 Merge pull request #629 from Sistemium/development
SocketAckManager thread-safe acks removal
2017-03-07 10:17:52 -05:00
Alexander Levin 99faafe723 SocketAckManager thread-safe acks removal 2017-03-06 19:57:19 +02:00
Erik Little efefecdbe3 Merge pull request #622 from Sistemium/development
thread-safe ack generation
2017-02-23 18:50:36 -05:00
Alexander Levin fcb2b6bbf6 thread-safe ack generation 2017-02-23 09:32:50 +02:00
Erik cce88ae3eb bump websocket 2017-02-12 12:13:21 -05:00
Erik Little 1616a58bd7 Fix building on xcode8.3 2017-01-30 12:13:02 -05:00
Erik 0fcb7903bb double encoding should be getting fixed, make the default false 2017-01-23 16:48:37 -05:00
Erik 3db37023c7 Merge branch 'master' into development
* master:
  Update SocketEngine.swift
  Update SocketEngine.swift
2017-01-23 16:44:02 -05:00
Erik Little e38bda7239 Merge pull request #602 from mephi1984/patch-1
Update SocketEngine.swift
2017-01-23 08:47:49 -05:00
Erik 9a05f794f7 bump websocket 2016-12-30 19:49:23 -05:00
Vladislav Khorev f943f41895 Update SocketEngine.swift
Fix issue #101
Place code in handleOpen, according to suggestion:
https://github.com/socketio/socket.io-client-swift/pull/602#issuecomment-269233001
2016-12-30 19:49:48 +03:00
Vladislav Khorev 494f3fa199 Update SocketEngine.swift
Fix issue #101
https://github.com/socketio/socket.io-client-swift/issues/101
2016-12-26 12:40:14 +03:00
Erik 0bb7fdd2eb bump version 2016-12-18 20:19:09 -05:00
Erik 650538ad2e Merge branch 'development'
* development:
  bump ws, fix #598
  remove namespace from socket id
2016-12-18 20:17:51 -05:00
Erik b1debdf912 bump ws, fix #598 2016-12-18 20:06:12 -05:00
Erik 077de02345 remove namespace from socket id 2016-11-24 08:15:17 -05:00
Erik 163a770abc bump version 2016-11-11 15:55:48 -05:00
Erik fc2a8e348c Merge branch 'development'
* development:
  Fix #562
2016-11-11 15:53:58 -05:00
Erik 56278795ea Merge branch 'development' of https://github.com/socketio/socket.io-client-swift into development
* 'development' of https://github.com/socketio/socket.io-client-swift:
  SocketAckEmitter.isExpected => .expected
  change isRequired() to isExpected()
  remove semicolon
  Update README.md
  add SocketAckEmitter.isRequired()
  Update README.md
  bump version
  bump websocket version
  fix Use Legacy Swift issue
  bump websocket version
  Update README.md
2016-11-11 15:52:48 -05:00
Erik a82f27ab8c Fix #562 2016-11-11 15:52:36 -05:00
Erik Little 2b8476ceca bump version 2016-10-28 11:53:02 -04:00
Erik Little 5ed4723535 Merge branch 'development'
* development:
  SocketAckEmitter.isExpected => .expected
  change isRequired() to isExpected()
  remove semicolon
  add SocketAckEmitter.isRequired()
  fix Use Legacy Swift issue
2016-10-28 11:51:58 -04:00
Erik Little b6aaa42337 Merge branch 'master' into development
* master:
  Update README.md
2016-10-28 11:51:46 -04:00
Erik Little e723604816 Merge pull request #544 from alexsun/patch-1
fix Use Legacy Swift issue
2016-10-28 11:46:46 -04:00
Erik Little 51ee9654da Merge pull request #557 from naderio/master
add SocketAckEmitter.expected to indicate if an ack is expected by server
2016-10-28 11:17:30 -04:00
Nader Toukabri ea3fca3767 SocketAckEmitter.isExpected => .expected 2016-10-28 15:59:50 +01:00
Nader Toukabri efad448fab change isRequired() to isExpected() 2016-10-28 15:14:07 +01:00
Nader Toukabri 018c993a9d remove semicolon 2016-10-28 15:09:21 +01:00
Erik Little 863480acf2 Update README.md 2016-10-28 09:43:46 -04:00
Nader Toukabri ff12285e94 add SocketAckEmitter.isRequired() 2016-10-28 14:23:22 +01:00
Nader Toukabri 51b95f9cee Merge pull request #1 from socketio/master
sync
2016-10-28 12:56:33 +01:00
Erik Little 86181525df Update README.md 2016-10-27 07:14:53 -04:00
Erik Little 85b6dc1766 bump version 2016-10-27 07:02:01 -04:00
Erik Little bc7ad37e62 Merge branch 'development'
* development:
  bump websocket version
  bump websocket version
  Fix #521
  add options to objective-c test
  add link to spm example
  remove redundant cast
  remove redundant cast
  Redo emitWithAck API since in Swift 3 parameter names aren't apart of the type
2016-10-27 06:38:56 -04:00
Erik Little 8042053331 bump websocket version 2016-10-27 06:37:39 -04:00
Jin Sun 0143dc25bf fix Use Legacy Swift issue 2016-10-18 17:29:01 +08:00
Erik Little 3e3ba60165 bump websocket version 2016-10-12 11:55:44 -04:00
Erik Little bd5c852fb6 Update README.md 2016-10-05 08:56:22 -04:00
Erik a32f2d34f0 Fix #521 2016-10-01 10:20:13 -04:00
Erik fee53e0ccf add options to objective-c test 2016-09-26 20:39:38 -04:00
Erik 2eb58fb262 add link to spm example 2016-09-25 14:51:54 -04:00
Erik 9ac6af95e3 Merge branch 'master' into development
* master:
  bump version
2016-09-25 13:39:14 -04:00
Erik b3da89d61c remove redundant cast 2016-09-25 12:10:29 -04:00
Erik c91a79fe5b remove redundant cast 2016-09-25 12:07:55 -04:00
Erik 6771f59ab7 Redo emitWithAck API since in Swift 3 parameter names aren't apart of the type 2016-09-25 11:59:10 -04:00
Erik 2faa2aeb95 bump version 2016-09-20 17:03:41 -04:00
Erik 04011a0a19 Merge branch 'development'
* development:
  fix objective-c
2016-09-20 17:01:41 -04:00
Erik 8ba3518fbc fix objective-c 2016-09-20 16:57:09 -04:00
Erik 0849a75686 bump version 2016-09-19 19:02:20 -04:00
Erik b33e73f119 bump websocket 2016-09-19 19:00:52 -04:00
Erik 549df19d4a Fix adding / to path 2016-09-19 18:52:13 -04:00
Erik 100a9730d2 rename file 2016-09-14 08:09:14 -04:00
Erik db35decac9 still try and fix cocoapods 2016-09-14 07:59:19 -04:00
Erik 2810e56162 Try and fix cocoapods 2016-09-14 07:54:55 -04:00
Erik 79e22b7d07 bump version 2016-09-14 07:22:27 -04:00
Erik 83ac8c9ac2 Merge branch 'development'
* development:
  We need to raise target version
2016-09-14 07:21:21 -04:00
Erik d3de97b584 Merge branch 'development' of https://github.com/socketio/socket.io-client-swift into development
* 'development' of https://github.com/socketio/socket.io-client-swift:
  We need to raise target version
2016-09-14 07:21:07 -04:00
Erik f051962e81 Merge branch 'development'
* development: (54 commits)
  refactor
  refactors
  clean up some things before xcode8 release
  remove testing of test branch
  Use xcodebuild until xctool is updated
  travis supports the gm
  update readme
  Turn off travis until it's updated
  Fix tests
  Fix truncation of binary data, use range operator for clarity
  Update for Xcode 8 GM
  Don't parse twice for errors
  use guarded try
  change spm name
  Modify mac version base mac os 10.9
  open socket manager
  refactor
  Fix swift3 errors that happened during merge
  Switch to using Any instead of AnyObject
  varios tweaks
  ...
2016-09-14 07:16:37 -04:00
Erik 723129b639 refactor 2016-09-14 07:16:22 -04:00
Erik Little 0183006c00 We need to raise target version 2016-09-12 08:10:12 -04:00
Erik 72b6565510 refactors 2016-09-10 10:12:37 -04:00
Erik 31adcd4728 clean up some things before xcode8 release 2016-09-10 09:17:50 -04:00
Erik fa4346cbc8 remove testing of test branch 2016-09-10 08:27:44 -04:00
Erik 9d0c03be10 Use xcodebuild until xctool is updated 2016-09-10 08:26:10 -04:00
Erik Little db999a58f2 travis supports the gm 2016-09-08 13:13:24 -04:00
Erik Little a137686163 update readme 2016-09-08 07:33:17 -04:00
Erik Little 6016129562 Turn off travis until it's updated 2016-09-08 07:31:17 -04:00
Erik Little a55e9ab3ba Merge branch 'development' into swift3
* development:
  Don't parse twice for errors
  use guarded try
  change spm name
  Modify mac version base mac os 10.9
2016-09-08 07:30:28 -04:00
Erik Little c5fd1c71be Merge branch 'parse-data-subrange' of https://github.com/CFKevinRef/socket.io-client-swift into swift3
* 'parse-data-subrange' of https://github.com/CFKevinRef/socket.io-client-swift:
  Fix truncation of binary data, use range operator for clarity
2016-09-08 07:23:20 -04:00
Erik Little 34ef8a5278 Fix tests 2016-09-08 07:23:00 -04:00
Kevin Cassidy Jr d808d8f157 Fix truncation of binary data, use range operator for clarity 2016-09-07 20:19:55 -07:00
Erik Little 259b453acb Merge pull request #484 from davbeck/swift3
Xcode 8 GM
2016-09-07 17:47:18 -04:00
David Beck bc929b7c26 Merge branch 'swift3' of github.com:socketio/socket.io-client-swift into swift3
# Conflicts:
#	Source/SocketTypes.swift
2016-09-07 14:21:10 -07:00
David Beck ffcf5fbf92 Update for Xcode 8 GM 2016-09-07 14:19:53 -07:00
Erik 16eefa4abf Don't parse twice for errors 2016-09-02 18:03:15 -04:00
Erik 49dfd7432c use guarded try 2016-09-02 17:57:26 -04:00
Erik 923103dec8 change spm name 2016-09-02 17:33:12 -04:00
Erik Little 81a82aae64 Merge pull request #479 from KobeStronger/feature/macVersion
Modify mac version base mac os 10.9
2016-09-02 09:06:06 -04:00
Kobe d3500d38ba Modify mac version base mac os 10.9 2016-09-02 10:46:39 +08:00
Erik a950656112 open socket manager 2016-08-31 20:45:15 -04:00
Erik c7d75b6b83 refactor 2016-08-31 19:58:40 -04:00
Erik f5cf2b8de5 Fix swift3 errors that happened during merge 2016-08-31 18:19:24 -04:00
Erik bd192b9af5 merge development 2016-08-31 18:13:31 -04:00
Erik a412eef268 Merge branch 'development'
* development:
  Fix cocoapods name
2016-08-29 05:21:55 -04:00
Erik 7d07e55ce5 Fix cocoapods name 2016-08-29 05:21:45 -04:00
Erik e8c3e22dc6 Merge branch 'development'
* development:
  fix sid bug
  Fix socketio/socket.io-client-swift#472
2016-08-29 05:10:58 -04:00
Erik cf12865aa0 fix sid bug 2016-08-29 05:10:03 -04:00
Erik 2200972f4d Fix socketio/socket.io-client-swift#472 2016-08-28 08:29:00 -04:00
Erik c7c824c3c5 bump version 2016-08-27 13:08:09 -04:00
Erik 89ab458a5f Merge branch 'development'
* development:
  Refactor engine. Fix infinite recursion in configuration
  Don't send whole packet to handleConnect
2016-08-27 13:07:26 -04:00
Erik bd7f94333d Refactor engine. Fix infinite recursion in configuration 2016-08-27 13:05:22 -04:00
Erik 4de7a48e87 Don't send whole packet to handleConnect 2016-08-27 11:37:13 -04:00
Erik e3c8cc7fd9 Update readme 2016-08-27 11:15:27 -04:00
Erik 4a9013d986 bump version 2016-08-27 11:10:56 -04:00
Erik 2910355245 Merge branch 'development'
* development:
  update readme
  Renamed modules to make then consistent.
  rename engine init
  tweaks
  Add SocketIOClientConfiguration
  Rename variable
  refactor some reconnect code
  bump websocket version
  move extensions
  refactor out checking for base64
2016-08-27 11:08:30 -04:00
Erik 23eb9a4dae Merge branch 'davbeck-swift3-any' into swift3
* davbeck-swift3-any:
  Switch to using Any instead of AnyObject
2016-08-24 06:54:57 -04:00
David Beck 59c158119a Merge branch 'swift3' of github.com:socketio/socket.io-client-swift into swift3
# Conflicts:
#	SocketIO-MacTests/SocketBasicPacketTest.swift
#	SocketIO-MacTests/SocketNamespacePacketTest.swift
#	Source/SocketExtensions.swift
#	Source/SocketPacket.swift
#	Source/WebSocket.swift
2016-08-23 10:53:50 -07:00
David Beck 536367392f Switch to using Any instead of AnyObject
In Swift 3 AnyObject is rarely what you want to use. Objective-C API gets imported as Any and while types like Array and Dictionary can be coerced to AnyObject, they prefer Any, which doesn’t require a manual cast.
2016-08-23 10:10:33 -07:00
Erik f982e756c2 varios tweaks 2016-08-20 17:58:52 -04:00
Erik 29670af4d3 fix crash 2016-08-20 16:16:57 -04:00
Erik 70b870690e Fix websocket 2016-08-20 15:30:07 -04:00
Erik 1232c34817 narrow down what's causing compiler crashes 2016-08-18 19:34:01 -04:00
Erik 9acae3b154 I'm not convinced this is right 2016-08-18 19:09:26 -04:00
Erik 0233f383bb Fix tests, this is broken for obvious reasons 2016-08-15 19:24:10 -04:00
Erik 3bf7a09f98 Swift 3 beta6. Doesn't work, something in websocket.swift is segfaulting the compiler 2016-08-15 18:52:25 -04:00
Erik 5e1dc53304 update readme 2016-08-14 23:05:02 -04:00
Erik Little e567067d44 Merge pull request #455 from drekka/development
Fixing inconsistent module names across iOS & tvOS
2016-08-14 23:03:27 -04:00
Derek Clarkson 518c256cc2 Renamed modules to make then consistent.
Remove base sources from test compiles.
2016-08-15 12:18:02 +10:00
Erik 07f2ca5f16 rename engine init 2016-08-14 11:06:55 -04:00
Erik d2cb8f2d9a fix conflict 2016-08-14 10:53:16 -04:00
Erik b8d6c28ae4 merge development 2016-08-14 10:51:44 -04:00
Erik c364f6a832 tweaks 2016-08-14 09:58:21 -04:00
Erik e2bf84f576 Add SocketIOClientConfiguration 2016-08-13 14:55:33 -04:00
Erik 64b9774c83 Move helper method 2016-08-13 13:32:14 -04:00
Erik ddd7003d89 merge development 2016-08-11 22:08:48 -04:00
Erik 437c983533 Rename variable 2016-08-11 21:26:01 -04:00
Erik 14b4df3836 refactor some reconnect code 2016-08-11 21:11:28 -04:00
Erik b6cb0b2c7b bump websocket version 2016-08-08 18:24:42 -04:00
Erik 81dfabbe15 Remove old files 2016-08-08 17:45:10 -04:00
Erik 3ec1b93f8e move extensions 2016-08-02 20:35:41 -04:00
Erik ee63c4e386 refactor out checking for base64 2016-08-02 20:14:04 -04:00
Erik 61a20cf27e update for beta 4 2016-08-02 19:38:08 -04:00
Erik a5db13c8b5 merge development 2016-07-29 20:06:43 -04:00
Erik 6147cda561 Merge branch 'development'
* development:
  bump version
  add check for bad paths
  Fix socketpollable crashing
  make nonobjc
  More privatisation
  Making publicKeyChainForTrust() private.
  api extensions doesn't seem to fail for me
  update readme
  don't use api extensions only
2016-07-29 19:38:16 -04:00
Erik fcfb409282 bump version 2016-07-29 19:34:22 -04:00
Erik d03d77aff8 add check for bad paths 2016-07-28 21:36:37 -04:00
Erik 637e0bb14c Fix socketpollable crashing 2016-07-27 21:16:48 -04:00
Erik Little 32ba61fb09 Merge branch 'drekka-development' into development
* drekka-development:
  make nonobjc
  More privatisation
  Making publicKeyChainForTrust() private.
  api extensions doesn't seem to fail for me
  update readme
2016-07-27 11:50:55 -04:00
Erik Little a9aa28ae77 make nonobjc 2016-07-27 11:50:44 -04:00
Derek Clarkson 99adb49736 More privatisation 2016-07-25 14:19:10 +10:00
Derek Clarkson 21d242ba6a Making publicKeyChainForTrust() private.
To Fixing issue when attempting to build for a objective-c project. Exposed API won’t compile so hiding internal method.
2016-07-25 13:41:26 +10:00
Erik 10d24c47ec api extensions doesn't seem to fail for me 2016-07-24 09:52:44 -04:00
Erik 604c30bf28 Merge branch 'development' of https://github.com/socketio/socket.io-client-swift into development
* 'development' of https://github.com/socketio/socket.io-client-swift:
  don't use api extensions only
  don't try and start server
  change travis config
  remove log for dorequest
2016-07-24 09:50:04 -04:00
Erik 1d56759276 update readme 2016-07-24 09:49:07 -04:00
Erik Little af77e984ab don't use api extensions only 2016-07-22 09:13:03 -04:00
Erik Little 1af7bd842e Revert "travis plz"
This reverts commit 7bd019fb28.
2016-07-21 11:15:20 -04:00
Erik Little 7bd019fb28 travis plz 2016-07-21 11:15:07 -04:00
Erik Little bb9ea1849a Merge branch 'development' into swift3
* development:
  don't try and start server
2016-07-21 10:52:15 -04:00
Erik Little cc449a49ea don't try and start server 2016-07-21 10:49:32 -04:00
Erik Little 4c8bfb91eb use a whitelist 2016-07-21 10:44:51 -04:00
Erik Little 3500211eed Merge branch 'development' into swift3
* development:
  change travis config
  remove log for dorequest
2016-07-21 10:44:11 -04:00
Erik Little b65b63a9f0 Merge branch 'master' into development
* master:
  change travis config
2016-07-21 10:42:30 -04:00
Erik Little 87c86f8aeb change travis config 2016-07-21 10:42:14 -04:00
Erik Little c9b60445ca remove log for dorequest 2016-07-21 10:28:20 -04:00
Erik 4ad3a884a6 merge development 2016-07-20 11:39:37 -04:00
Erik f15a6dc491 bump version 2016-07-20 11:25:45 -04:00
Erik 7fb2193032 fix swiftpm 2016-07-20 11:22:05 -04:00
Erik 8df6eeb85a Merge branch 'aputinski-swift3' into swift3
* aputinski-swift3:
  update tests, add test for base64
  Fix Xcode 8 Beta 3 issues/warnings
  Use Legacy Swift Language Version
  Enable APPLICATION_EXTENSION_API_ONLY
2016-07-20 11:08:00 -04:00
Erik 4ad5025c77 update tests, add test for base64 2016-07-20 11:07:37 -04:00
Adam Putinski 777fa30c76 Fix Xcode 8 Beta 3 issues/warnings 2016-07-19 23:01:59 -04:00
Adam Putinski f214de1407 Use Legacy Swift Language Version 2016-07-19 22:37:56 -04:00
Erik Little e56741b669 rename variable 2016-07-19 15:03:03 -04:00
Adam Putinski 559fbc0286 Enable APPLICATION_EXTENSION_API_ONLY 2016-07-19 09:15:28 -04:00
Erik Little dcf206b0f1 Merge pull request #422 from aputinski/api-extensions-only
Enable APPLICATION_EXTENSION_API_ONLY
2016-07-19 09:11:30 -04:00
Erik e961e11487 change another method name 2016-07-16 22:27:50 -04:00
Erik f140d7979e change method name 2016-07-16 21:27:18 -04:00
Erik afa27e4173 get readme ready for swift3 2016-07-16 21:06:22 -04:00
Erik Little a9ac86ba3d fix method call 2016-07-15 10:11:05 -04:00
Erik f3d771641d some swift3 changes 2016-07-14 19:54:09 -04:00
Erik f6dc11650d merge development 2016-07-14 19:36:48 -04:00
Erik dce28b2dac fixes 2016-07-14 19:26:56 -04:00
Erik 8345eae28c don't stall queues 2016-07-14 19:25:48 -04:00
Erik e8219e6b6a merge development 2016-07-14 19:12:03 -04:00
Erik 9cc60ab63d hopefully fix race condition in acks 2016-07-14 18:57:27 -04:00
Adam Putinski 3828211446 Enable APPLICATION_EXTENSION_API_ONLY 2016-07-13 06:34:02 -04:00
Erik 36aa57e89c beta2 2016-07-06 11:47:25 -04:00
Erik 22030e1153 refactors 2016-07-06 11:19:18 -04:00
Erik 73b042b41e Merge branch 'master' into development
* master:
  Update README.md
2016-07-01 17:06:59 -04:00
Erik Little f52607f722 Update README.md 2016-07-01 17:06:37 -04:00
Erik f00ed17783 refactors, rename file 2016-07-01 15:42:13 -04:00
Erik 5840d2b61b refactoring 2016-07-01 15:38:53 -04:00
Erik 17d3e659c1 refactor some serialization into methods 2016-07-01 15:36:06 -04:00
Erik c129118496 merge development 2016-06-24 02:53:31 -04:00
Erik 2a0ce72792 small swift 3 changes 2016-06-22 10:04:27 -04:00
Erik bddc9dc6aa fix logging 2016-06-15 11:00:21 -04:00
Erik 7c3de9f30a even more xcode 8 stuff. style changes 2016-06-15 10:13:44 -04:00
Erik 2adcf2d35d more xcode 8 stuff 2016-06-15 09:32:47 -04:00
Erik 9a4ec5a82a xcode 8 2016-06-14 20:41:59 -04:00
Erik 7500ea83a0 merge development 2016-06-14 19:51:56 -04:00
Erik 523ced2f9a merge development 2016-06-09 09:37:26 -04:00
Erik aae61f3b2e Merge development 2016-06-01 11:17:19 -04:00
Erik d88bb43d9c some methods have discardableresults 2016-06-01 11:13:05 -04:00
Erik 3b4a3828ba fix for ackemitter 2016-05-22 14:17:01 -04:00
Erik c6d000972e add test 2016-05-22 14:10:43 -04:00
Erik 51ee4d3d1d try and avoid a bunch of as AnyObject nonsense 2016-05-22 14:05:01 -04:00
Erik 044d9c0746 remove 2016-05-21 12:41:08 -04:00
Erik 593db4cd8d update readme 2016-05-21 11:59:16 -04:00
Erik f90ad8caeb update for latest swift 2016-05-21 11:45:35 -04:00
Erik 95cd24a124 remove swiftregex 2016-05-05 13:36:34 -04:00
Erik 6452f6a97a merge dev 2016-05-05 13:33:52 -04:00
Erik e2db1a086d update for latest swift 3 2016-04-16 12:00:21 -04:00
Erik 9f8db42584 Merge branch 'development' into swift3
* development:
  expose ws
  rename file
  change to how server gives id
2016-04-16 11:11:05 -04:00
Erik 376e31bfca merge development and fix tests 2016-04-10 14:15:35 -04:00
Erik 3735dd0e6a Merge branch 'development' into swift3
* development:
  set targetted device family to 3
  use 7.3 image
2016-03-25 17:03:12 -04:00
Erik 199b9962f0 swift3 naming 2016-03-25 13:11:28 -04:00
Erik 4d4362b250 work on swift3 syntax 2016-03-25 12:59:50 -04:00
45 changed files with 2412 additions and 2077 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
3.1
+9 -9
View File
@@ -1,13 +1,13 @@
language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode7.3
osx_image: xcode8.3
branches:
only:
- master
- development
before_install:
- cd Socket.IO-Test-Server/
- npm install
- cd ..
install: node Socket.IO-Test-Server/main.js &
script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
cache:
directories:
- Socket.IO-Test-Server/node_modules
- brew update
- brew outdated xctool || brew upgrade xctool
# script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
script: xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test
+1 -1
View File
@@ -1,5 +1,5 @@
import PackageDescription
let package = Package(
name: "SocketIOClientSwift"
name: "SocketIO"
)
+57 -48
View File
@@ -5,7 +5,9 @@ Socket.IO-client for iOS/OS X.
##Example
```swift
let socket = SocketIOClient(socketURL: NSURL(string: "http://localhost:8080")!, options: [.Log(true), .ForcePolling(true)])
import SocketIO
let socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .forcePolling(true)])
socket.on("connect") {data, ack in
print("socket connected")
@@ -13,7 +15,7 @@ socket.on("connect") {data, ack in
socket.on("currentAmount") {data, ack in
if let cur = data[0] as? Double {
socket.emitWithAck("canUpdate", cur)(timeoutAfter: 0) {data in
socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
socket.emit("update", ["amount": cur + 2.50])
}
@@ -26,8 +28,9 @@ socket.connect()
##Objective-C Example
```objective-c
@import SocketIO;
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:8080"];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@{@"log": @YES, @"forcePolling": @YES}];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
NSLog(@"socket connected");
@@ -36,9 +39,9 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@
[socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
double cur = [[data objectAtIndex:0] floatValue];
[socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
[[socket emitWithAck:@"canUpdate" with:@[@(cur)]] timingOutAfter:0 callback:^(NSArray* data) {
[socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
});
}];
[ack with:@[@"Got your currentAmount, ", @"dude"]];
}];
@@ -55,13 +58,17 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@
- Can be used from Objective-C
##Installation
Requires Swift 2.2/Xcode 7.3
Requires Swift 3/Xcode 8.x
If you need Swift 2.1/Xcode 7.2 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
If you need swift 2.3 use the swift2.3 tag (Pre-Swift 3 support is no longer maintained)
If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
If you need swift 2.2 use 7.x (Pre-Swift 3 support is no longer maintained)
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
If you need Swift 2.1 use v5.5.0 (Pre-Swift 2.2 support is no longer maintained)
If you need Swift 1.2 use v2.4.5 (Pre-Swift 2 support is no longer maintained)
If you need Swift 1.1 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
Manually (iOS 7+)
-----------------
@@ -77,32 +84,32 @@ import PackageDescription
let package = Package(
name: "YourSocketIOProject",
dependencies: [
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 6)
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 8)
]
)
```
Then import `import SocketIOClientSwift`.
Then import `import SocketIO`.
Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 6.1.4 # Or latest version
github "socketio/socket.io-client-swift" ~> 8.3.3 # Or latest version
```
Run `carthage update --platform ios,macosx`.
CocoaPods 0.36.0 or later (iOS 8+)
CocoaPods 1.0.0 or later
------------------
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 6.1.4' # Or latest version
target 'YourApp' do
pod 'Socket.IO-Client-Swift', '~> 8.3.3' # Or latest version
end
```
Install pods:
@@ -115,13 +122,13 @@ Import the module:
Swift:
```swift
import SocketIOClientSwift
import SocketIO
```
Objective-C:
```Objective-C
#import <SocketIOClientSwift/SocketIOClientSwift-Swift.h>
@import SocketIO;
```
CocoaSeeds
@@ -130,7 +137,7 @@ CocoaSeeds
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v6.1.4", :files => "Source/*.swift" # Or latest version
github "socketio/socket.io-client-swift", "v8.3.3", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
@@ -139,7 +146,7 @@ Run `seed install`.
##API
Constructors
-----------
`init(var socketURL: NSURL, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. options is a Set of SocketIOClientOption. If your socket.io server is secure, you need to specify `https` in your socketURL.
`init(var socketURL: NSURL, config: SocketIOClientConfiguration = [])` - Creates a new SocketIOClient. If your socket.io server is secure, you need to specify `https` in your socketURL.
`convenience init(socketURL: NSURL, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
@@ -148,43 +155,43 @@ Options
All options are a case of SocketIOClientOption. To get the Objective-C Option, convert the name to lowerCamelCase.
```swift
case ConnectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
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 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 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 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 Security(SSLSecurity) // Allows you to set which certs are valid. Useful for SSL pinning.
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
case connectParams([String: AnyObject]) // Dictionary whose contents will be passed with the connection.
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 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 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 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 security(SSLSecurity) // Allows you to set which certs are valid. Useful for SSL pinning.
case selfSigned(Bool) // Sets WebSocket.selfSignedSSL. Use this if you're using self-signed certs.
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
-------
1. `on(event: String, callback: NormalCallback) -> NSUUID` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example. Returns a unique id for the handler.
2. `once(event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
1. `on(_ event: String, callback: NormalCallback) -> NSUUID` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example. Returns a unique id for the handler.
2. `once(_ event: String, callback: NormalCallback) -> NSUUID` - Adds a handler that will only be executed once. Returns a unique id for the handler.
3. `onAny(callback:((event: String, items: AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
4. `emit(event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
5. `emit(event: String, withItems items: [AnyObject])` - `emit` for Objective-C
6. `emitWithAck(event: String, _ items: AnyObject...) -> (timeoutAfter: UInt64, callback: (NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
7. `emitWithAck(event: String, withItems items: [AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
4. `emit(_ event: String, _ items: AnyObject...)` - Sends a message. Can send multiple items.
5. `emit(_ event: String, withItems items: [AnyObject])` - `emit` for Objective-C
6. `emitWithAck(_ event: String, _ items: AnyObject...) -> OnAckCallback` - Sends a message that requests an acknowledgement from the server. Returns an object which you can use to add a handler. See example. Note: The message is not sent until you call timingOut(after:) on the returned object.
7. `emitWithAck(_ event: String, withItems items: [AnyObject]) -> OnAckCallback` - `emitWithAck` for Objective-C. Note: The message is not sent until you call timingOutAfter on the returned object.
8. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
9. `connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
10. `disconnect()` - Closes the socket. Reopening a disconnected socket is not fully tested.
11. `reconnect()` - Causes the client to reconnect to the server.
12. `joinNamespace(namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces manually.
12. `joinNamespace(_ namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces manually.
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
14. `off(event: String)` - Removes all event handlers for event.
14. `off(_ event: String)` - Removes all event handlers for event.
15. `off(id id: NSUUID)` - Removes the event that corresponds to id.
16. `removeAllHandlers()` - Removes all handlers.
@@ -199,5 +206,7 @@ Client Events
##Detailed Example
A more detailed example can be found [here](https://github.com/nuclearace/socket.io-client-swift-example)
An example using the Swift Package Manager can be found [here](https://github.com/nuclearace/socket.io-client-swift-spm-example)
##License
MIT
+4 -3
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.module_name = "SocketIOClientSwift"
s.version = "6.1.4"
s.module_name = "SocketIO"
s.version = "8.3.3"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
@@ -14,8 +14,9 @@ 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 => 'v6.1.4' }
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v8.3.3' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
s.pod_target_xcconfig = {'SWIFT_VERSION' => '3.1'}
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
+148 -131
View File
@@ -7,100 +7,70 @@
objects = {
/* Begin PBXBuildFile section */
572EF21F1B51F16C00EEBB58 /* SocketIO-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2251B51F16C00EEBB58 /* SocketIOClientSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */; };
572EF21F1B51F16C00EEBB58 /* SocketIO.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2251B51F16C00EEBB58 /* SocketIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2191B51F16C00EEBB58 /* SocketIO.framework */; };
572EF23D1B51F18A00EEBB58 /* SocketIO-Mac.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF23C1B51F18A00EEBB58 /* SocketIO-Mac.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2431B51F18A00EEBB58 /* SocketIOClientSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */; };
57634A111BD9B46A00E19CD7 /* SocketIO-iOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
572EF2431B51F18A00EEBB58 /* SocketIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 572EF2381B51F18A00EEBB58 /* SocketIO.framework */; };
57634A111BD9B46A00E19CD7 /* SocketIO.h in Headers */ = {isa = PBXBuildFile; fileRef = 572EF21E1B51F16C00EEBB58 /* SocketIO.h */; settings = {ATTRIBUTES = (Public, ); }; };
57634A231BD9B46D00E19CD7 /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
57634A2F1BD9B46D00E19CD7 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
57634A321BD9B46D00E19CD7 /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
57634A3F1BD9B4BF00E19CD7 /* SocketIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 57634A161BD9B46A00E19CD7 /* SocketIO.framework */; };
6CA08A961D615C040061FD2A /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6CA08A951D615C040061FD2A /* Security.framework */; };
6CA08A981D615C0B0061FD2A /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6CA08A971D615C0B0061FD2A /* Security.framework */; };
6CA08A9A1D615C140061FD2A /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6CA08A991D615C140061FD2A /* Security.framework */; };
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */; };
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */; };
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */; };
74171E631C10CD240062D398 /* SocketAckEmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E501C10CD240062D398 /* SocketAckEmitter.swift */; };
74171E641C10CD240062D398 /* SocketAckEmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E501C10CD240062D398 /* SocketAckEmitter.swift */; };
74171E651C10CD240062D398 /* SocketAckEmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E501C10CD240062D398 /* SocketAckEmitter.swift */; };
74171E671C10CD240062D398 /* SocketAckEmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E501C10CD240062D398 /* SocketAckEmitter.swift */; };
74171E681C10CD240062D398 /* SocketAckEmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E501C10CD240062D398 /* SocketAckEmitter.swift */; };
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E511C10CD240062D398 /* SocketAckManager.swift */; };
74171E6A1C10CD240062D398 /* SocketAckManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E511C10CD240062D398 /* SocketAckManager.swift */; };
74171E6B1C10CD240062D398 /* SocketAckManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E511C10CD240062D398 /* SocketAckManager.swift */; };
74171E6D1C10CD240062D398 /* SocketAckManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E511C10CD240062D398 /* SocketAckManager.swift */; };
74171E6E1C10CD240062D398 /* SocketAckManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E511C10CD240062D398 /* SocketAckManager.swift */; };
74171E6F1C10CD240062D398 /* SocketAnyEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E521C10CD240062D398 /* SocketAnyEvent.swift */; };
74171E701C10CD240062D398 /* SocketAnyEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E521C10CD240062D398 /* SocketAnyEvent.swift */; };
74171E711C10CD240062D398 /* SocketAnyEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E521C10CD240062D398 /* SocketAnyEvent.swift */; };
74171E731C10CD240062D398 /* SocketAnyEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E521C10CD240062D398 /* SocketAnyEvent.swift */; };
74171E741C10CD240062D398 /* SocketAnyEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E521C10CD240062D398 /* SocketAnyEvent.swift */; };
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E531C10CD240062D398 /* SocketEngine.swift */; };
74171E761C10CD240062D398 /* SocketEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E531C10CD240062D398 /* SocketEngine.swift */; };
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E531C10CD240062D398 /* SocketEngine.swift */; };
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E531C10CD240062D398 /* SocketEngine.swift */; };
74171E7A1C10CD240062D398 /* SocketEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E531C10CD240062D398 /* SocketEngine.swift */; };
74171E7B1C10CD240062D398 /* SocketEngineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E541C10CD240062D398 /* SocketEngineClient.swift */; };
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E541C10CD240062D398 /* SocketEngineClient.swift */; };
74171E7D1C10CD240062D398 /* SocketEngineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E541C10CD240062D398 /* SocketEngineClient.swift */; };
74171E7F1C10CD240062D398 /* SocketEngineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E541C10CD240062D398 /* SocketEngineClient.swift */; };
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E541C10CD240062D398 /* SocketEngineClient.swift */; };
74171E811C10CD240062D398 /* SocketEnginePacketType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E551C10CD240062D398 /* SocketEnginePacketType.swift */; };
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E551C10CD240062D398 /* SocketEnginePacketType.swift */; };
74171E831C10CD240062D398 /* SocketEnginePacketType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E551C10CD240062D398 /* SocketEnginePacketType.swift */; };
74171E851C10CD240062D398 /* SocketEnginePacketType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E551C10CD240062D398 /* SocketEnginePacketType.swift */; };
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E551C10CD240062D398 /* SocketEnginePacketType.swift */; };
74171E871C10CD240062D398 /* SocketEngineSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E561C10CD240062D398 /* SocketEngineSpec.swift */; };
74171E881C10CD240062D398 /* SocketEngineSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E561C10CD240062D398 /* SocketEngineSpec.swift */; };
74171E891C10CD240062D398 /* SocketEngineSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E561C10CD240062D398 /* SocketEngineSpec.swift */; };
74171E8B1C10CD240062D398 /* SocketEngineSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E561C10CD240062D398 /* SocketEngineSpec.swift */; };
74171E8C1C10CD240062D398 /* SocketEngineSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E561C10CD240062D398 /* SocketEngineSpec.swift */; };
74171E8D1C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E571C10CD240062D398 /* SocketEventHandler.swift */; };
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 */; };
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 */; };
74171E9D1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9E1C10CD240062D398 /* SocketIOClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E591C10CD240062D398 /* SocketIOClient.swift */; };
74171E9F1C10CD240062D398 /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */; };
74171EA01C10CD240062D398 /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */; };
74171EA11C10CD240062D398 /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */; };
74171EA31C10CD240062D398 /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */; };
74171EA41C10CD240062D398 /* SocketIOClientOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */; };
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EA61C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EA81C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EAA1C10CD240062D398 /* SocketIOClientStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */; };
74171EAB1C10CD240062D398 /* SocketLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5C1C10CD240062D398 /* SocketLogger.swift */; };
74171EAC1C10CD240062D398 /* SocketLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5C1C10CD240062D398 /* SocketLogger.swift */; };
74171EAD1C10CD240062D398 /* SocketLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5C1C10CD240062D398 /* SocketLogger.swift */; };
74171EAF1C10CD240062D398 /* SocketLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5C1C10CD240062D398 /* SocketLogger.swift */; };
74171EB01C10CD240062D398 /* SocketLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5C1C10CD240062D398 /* SocketLogger.swift */; };
74171EB11C10CD240062D398 /* SocketPacket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5D1C10CD240062D398 /* SocketPacket.swift */; };
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5D1C10CD240062D398 /* SocketPacket.swift */; };
74171EB31C10CD240062D398 /* SocketPacket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5D1C10CD240062D398 /* SocketPacket.swift */; };
74171EB51C10CD240062D398 /* SocketPacket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5D1C10CD240062D398 /* SocketPacket.swift */; };
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5D1C10CD240062D398 /* SocketPacket.swift */; };
74171EB71C10CD240062D398 /* SocketParsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5E1C10CD240062D398 /* SocketParsable.swift */; };
74171EB81C10CD240062D398 /* SocketParsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5E1C10CD240062D398 /* SocketParsable.swift */; };
74171EB91C10CD240062D398 /* SocketParsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5E1C10CD240062D398 /* SocketParsable.swift */; };
74171EBB1C10CD240062D398 /* SocketParsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5E1C10CD240062D398 /* SocketParsable.swift */; };
74171EBC1C10CD240062D398 /* SocketParsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5E1C10CD240062D398 /* SocketParsable.swift */; };
74171EBD1C10CD240062D398 /* SocketStringReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5F1C10CD240062D398 /* SocketStringReader.swift */; };
74171EBE1C10CD240062D398 /* SocketStringReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5F1C10CD240062D398 /* SocketStringReader.swift */; };
74171EBF1C10CD240062D398 /* SocketStringReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5F1C10CD240062D398 /* SocketStringReader.swift */; };
74171EC11C10CD240062D398 /* SocketStringReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5F1C10CD240062D398 /* SocketStringReader.swift */; };
74171EC21C10CD240062D398 /* SocketStringReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E5F1C10CD240062D398 /* SocketStringReader.swift */; };
74171EC31C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
74171EC41C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
74171EC51C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
74171EC71C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74171E601C10CD240062D398 /* SocketTypes.swift */; };
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
741F39EF1BD025D80026C9CC /* SocketEngineTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */; };
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7420CB781C49629E00956AA4 /* SocketEnginePollable.swift */; };
@@ -115,24 +85,25 @@
7472C65D1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */; };
7472C65F1BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */; };
747BC5991D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 747BC5981D5F943500CA5FA4 /* SocketIOClientConfiguration.swift */; };
747BC59A1D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 747BC5981D5F943500CA5FA4 /* SocketIOClientConfiguration.swift */; };
747BC59B1D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 747BC5981D5F943500CA5FA4 /* SocketIOClientConfiguration.swift */; };
747BC59F1D5F9BA200CA5FA4 /* SocketIOClientConfigurationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 747BC59E1D5F9BA200CA5FA4 /* SocketIOClientConfigurationTest.swift */; };
749642B51D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B31D3FCE5500DD32D1 /* SSLSecurity.swift */; };
749642B61D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B31D3FCE5500DD32D1 /* SSLSecurity.swift */; };
749642B71D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B31D3FCE5500DD32D1 /* SSLSecurity.swift */; };
749642B81D3FCE5500DD32D1 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B41D3FCE5500DD32D1 /* WebSocket.swift */; };
749642B91D3FCE5500DD32D1 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B41D3FCE5500DD32D1 /* WebSocket.swift */; };
749642BA1D3FCE5500DD32D1 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 749642B41D3FCE5500DD32D1 /* WebSocket.swift */; };
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */; };
74B4AD1D1D09A5D80062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
74B4AD211D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
74B4AD221D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
74B4AD231D09A6190062A523 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD201D09A6190062A523 /* SSLSecurity.swift */; };
74B4AD241D09A6450062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
74B4AD251D09A6490062A523 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B4AD1C1D09A5D80062A523 /* WebSocket.swift */; };
74BC45AB1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
74BC45AC1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
74BC45AD1D0C6675008CC431 /* SocketClientManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */; };
74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */; };
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */; };
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* String.swift */; };
CEBA569A1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* SocketExtensions.swift */; };
CEBA569B1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* SocketExtensions.swift */; };
CEBA569C1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEBA56991CDA0B8200BA0389 /* SocketExtensions.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -160,17 +131,20 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIOClientSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2191B51F16C00EEBB58 /* SocketIO.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIO.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF21D1B51F16C00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-iOS.h"; sourceTree = "<group>"; };
572EF21E1B51F16C00EEBB58 /* SocketIO.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SocketIO.h; sourceTree = "<group>"; };
572EF2241B51F16C00EEBB58 /* SocketIO-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIOClientSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2381B51F18A00EEBB58 /* SocketIO.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIO.framework; sourceTree = BUILT_PRODUCTS_DIR; };
572EF23B1B51F18A00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
572EF23C1B51F18A00EEBB58 /* SocketIO-Mac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SocketIO-Mac.h"; sourceTree = "<group>"; };
572EF2421B51F18A00EEBB58 /* SocketIO-MacTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-MacTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
572EF2481B51F18A00EEBB58 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
57634A161BD9B46A00E19CD7 /* SocketIO.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SocketIO.framework; sourceTree = BUILT_PRODUCTS_DIR; };
57634A3B1BD9B46D00E19CD7 /* SocketIO-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SocketIO-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
6CA08A951D615C040061FD2A /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; };
6CA08A971D615C0B0061FD2A /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
6CA08A991D615C140061FD2A /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS9.2.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; };
740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SocketEngineWebsocket.swift; path = Source/SocketEngineWebsocket.swift; sourceTree = "<group>"; };
74171E501C10CD240062D398 /* SocketAckEmitter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketAckEmitter.swift; path = Source/SocketAckEmitter.swift; sourceTree = "<group>"; };
74171E511C10CD240062D398 /* SocketAckManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketAckManager.swift; path = Source/SocketAckManager.swift; sourceTree = "<group>"; };
@@ -195,13 +169,14 @@
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocketParserTest.swift; sourceTree = "<group>"; };
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketNamespacePacketTest.swift; sourceTree = "<group>"; };
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketSideEffectTest.swift; sourceTree = "<group>"; };
747BC5981D5F943500CA5FA4 /* SocketIOClientConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientConfiguration.swift; path = Source/SocketIOClientConfiguration.swift; sourceTree = "<group>"; };
747BC59E1D5F9BA200CA5FA4 /* SocketIOClientConfigurationTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketIOClientConfigurationTest.swift; sourceTree = "<group>"; };
749642B31D3FCE5500DD32D1 /* SSLSecurity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Source/SSLSecurity.swift; sourceTree = "<group>"; };
749642B41D3FCE5500DD32D1 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket.swift; sourceTree = "<group>"; };
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketIOClientSpec.swift; path = Source/SocketIOClientSpec.swift; sourceTree = "<group>"; };
74B4AD1C1D09A5D80062A523 /* WebSocket.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Source/WebSocket/WebSocket.swift; sourceTree = "<group>"; };
74B4AD201D09A6190062A523 /* SSLSecurity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Source/WebSocket/SSLSecurity.swift; sourceTree = "<group>"; };
74BC45AA1D0C6675008CC431 /* SocketClientManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketClientManager.swift; path = Source/SocketClientManager.swift; sourceTree = "<group>"; };
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocketBasicPacketTest.swift; sourceTree = "<group>"; };
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NSCharacterSet.swift; path = Source/NSCharacterSet.swift; sourceTree = "<group>"; };
CEBA56991CDA0B8200BA0389 /* String.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = String.swift; path = Source/String.swift; sourceTree = "<group>"; };
CEBA56991CDA0B8200BA0389 /* SocketExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SocketExtensions.swift; path = Source/SocketExtensions.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -209,6 +184,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
6CA08A961D615C040061FD2A /* Security.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -216,7 +192,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
572EF2251B51F16C00EEBB58 /* SocketIOClientSwift.framework in Frameworks */,
572EF2251B51F16C00EEBB58 /* SocketIO.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -224,6 +200,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
6CA08A981D615C0B0061FD2A /* Security.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -231,7 +208,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
572EF2431B51F18A00EEBB58 /* SocketIOClientSwift.framework in Frameworks */,
572EF2431B51F18A00EEBB58 /* SocketIO.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -239,6 +216,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
6CA08A9A1D615C140061FD2A /* Security.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -256,20 +234,21 @@
572EF20D1B51F12F00EEBB58 = {
isa = PBXGroup;
children = (
5764DF7B1B51F24A004FF46E /* Source */,
6CA08A9B1D615C190061FD2A /* Frameworks */,
572EF21A1B51F16C00EEBB58 /* Products */,
572EF21B1B51F16C00EEBB58 /* SocketIO-iOS */,
572EF2391B51F18A00EEBB58 /* SocketIO-Mac */,
572EF2461B51F18A00EEBB58 /* SocketIO-MacTests */,
572EF21A1B51F16C00EEBB58 /* Products */,
5764DF7B1B51F24A004FF46E /* Source */,
);
sourceTree = "<group>";
};
572EF21A1B51F16C00EEBB58 /* Products */ = {
isa = PBXGroup;
children = (
572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */,
572EF2191B51F16C00EEBB58 /* SocketIO.framework */,
572EF2241B51F16C00EEBB58 /* SocketIO-iOSTests.xctest */,
572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */,
572EF2381B51F18A00EEBB58 /* SocketIO.framework */,
572EF2421B51F18A00EEBB58 /* SocketIO-MacTests.xctest */,
57634A161BD9B46A00E19CD7 /* SocketIO.framework */,
57634A3B1BD9B46D00E19CD7 /* SocketIO-tvOSTests.xctest */,
@@ -280,7 +259,7 @@
572EF21B1B51F16C00EEBB58 /* SocketIO-iOS */ = {
isa = PBXGroup;
children = (
572EF21E1B51F16C00EEBB58 /* SocketIO-iOS.h */,
572EF21E1B51F16C00EEBB58 /* SocketIO.h */,
572EF21C1B51F16C00EEBB58 /* Supporting Files */,
);
path = "SocketIO-iOS";
@@ -318,6 +297,7 @@
74F124EF1BC574CF002966F4 /* SocketBasicPacketTest.swift */,
741F39ED1BD025D80026C9CC /* SocketEngineTest.swift */,
7472C65B1BCAB53E003CA70D /* SocketNamespacePacketTest.swift */,
747BC59E1D5F9BA200CA5FA4 /* SocketIOClientConfigurationTest.swift */,
742D150B1CA5794B00BD987D /* SocketObjectiveCTest.m */,
74321DCA1C2D939A00CF6F43 /* SocketParserTest.swift */,
7472C65E1BCAC46E003CA70D /* SocketSideEffectTest.swift */,
@@ -348,7 +328,9 @@
74171E561C10CD240062D398 /* SocketEngineSpec.swift */,
740CA11F1C496EEB00CB98F4 /* SocketEngineWebsocket.swift */,
74171E571C10CD240062D398 /* SocketEventHandler.swift */,
CEBA56991CDA0B8200BA0389 /* SocketExtensions.swift */,
74171E591C10CD240062D398 /* SocketIOClient.swift */,
747BC5981D5F943500CA5FA4 /* SocketIOClientConfiguration.swift */,
74171E5A1C10CD240062D398 /* SocketIOClientOption.swift */,
74ABF7761C3991C10078C657 /* SocketIOClientSpec.swift */,
74171E5B1C10CD240062D398 /* SocketIOClientStatus.swift */,
@@ -357,30 +339,54 @@
74171E5E1C10CD240062D398 /* SocketParsable.swift */,
74171E5F1C10CD240062D398 /* SocketStringReader.swift */,
74171E601C10CD240062D398 /* SocketTypes.swift */,
CEBA569E1CDA0C0C00BA0389 /* utils */,
74B4AD1B1D09A5C30062A523 /* Websocket */,
);
name = Source;
sourceTree = "<group>";
};
6CA08A9B1D615C190061FD2A /* Frameworks */ = {
isa = PBXGroup;
children = (
6CA08A9E1D615C340061FD2A /* tvOS */,
6CA08A9D1D615C2C0061FD2A /* Mac */,
6CA08A9C1D615C270061FD2A /* iOS */,
);
name = Frameworks;
sourceTree = "<group>";
};
6CA08A9C1D615C270061FD2A /* iOS */ = {
isa = PBXGroup;
children = (
6CA08A951D615C040061FD2A /* Security.framework */,
);
name = iOS;
sourceTree = "<group>";
};
6CA08A9D1D615C2C0061FD2A /* Mac */ = {
isa = PBXGroup;
children = (
6CA08A971D615C0B0061FD2A /* Security.framework */,
);
name = Mac;
sourceTree = "<group>";
};
6CA08A9E1D615C340061FD2A /* tvOS */ = {
isa = PBXGroup;
children = (
6CA08A991D615C140061FD2A /* Security.framework */,
);
name = tvOS;
sourceTree = "<group>";
};
74B4AD1B1D09A5C30062A523 /* Websocket */ = {
isa = PBXGroup;
children = (
74B4AD1C1D09A5D80062A523 /* WebSocket.swift */,
74B4AD201D09A6190062A523 /* SSLSecurity.swift */,
749642B31D3FCE5500DD32D1 /* SSLSecurity.swift */,
749642B41D3FCE5500DD32D1 /* WebSocket.swift */,
);
name = Websocket;
sourceTree = "<group>";
};
CEBA569E1CDA0C0C00BA0389 /* utils */ = {
isa = PBXGroup;
children = (
CEBA56951CDA0B7700BA0389 /* NSCharacterSet.swift */,
CEBA56991CDA0B8200BA0389 /* String.swift */,
);
name = utils;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
@@ -388,7 +394,7 @@
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
572EF21F1B51F16C00EEBB58 /* SocketIO-iOS.h in Headers */,
572EF21F1B51F16C00EEBB58 /* SocketIO.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -404,7 +410,7 @@
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
57634A111BD9B46A00E19CD7 /* SocketIO-iOS.h in Headers */,
57634A111BD9B46A00E19CD7 /* SocketIO.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -426,7 +432,7 @@
);
name = "SocketIO-iOS";
productName = "SocketIO-iOS";
productReference = 572EF2191B51F16C00EEBB58 /* SocketIOClientSwift.framework */;
productReference = 572EF2191B51F16C00EEBB58 /* SocketIO.framework */;
productType = "com.apple.product-type.framework";
};
572EF2231B51F16C00EEBB58 /* SocketIO-iOSTests */ = {
@@ -462,7 +468,7 @@
);
name = "SocketIO-Mac";
productName = "SocketIO-Mac";
productReference = 572EF2381B51F18A00EEBB58 /* SocketIOClientSwift.framework */;
productReference = 572EF2381B51F18A00EEBB58 /* SocketIO.framework */;
productType = "com.apple.product-type.framework";
};
572EF2411B51F18A00EEBB58 /* SocketIO-MacTests */ = {
@@ -525,8 +531,9 @@
572EF20E1B51F12F00EEBB58 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftMigration = 0730;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0720;
LastUpgradeCheck = 0800;
TargetAttributes = {
572EF2181B51F16C00EEBB58 = {
CreatedOnToolsVersion = 6.4;
@@ -536,9 +543,11 @@
};
572EF2371B51F18A00EEBB58 = {
CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0800;
};
572EF2411B51F18A00EEBB58 = {
CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0800;
};
};
};
@@ -616,26 +625,26 @@
files = (
740CA1221C496EF700CB98F4 /* SocketEngineWebsocket.swift in Sources */,
74171EA51C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
CEBA569A1CDA0B8200BA0389 /* String.swift in Sources */,
74B4AD1D1D09A5D80062A523 /* WebSocket.swift in Sources */,
CEBA569A1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */,
74171E751C10CD240062D398 /* SocketEngine.swift in Sources */,
74171E691C10CD240062D398 /* SocketAckManager.swift in Sources */,
7420CB791C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
CEBA56961CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
74ABF7771C3991C10078C657 /* SocketIOClientSpec.swift in Sources */,
74171E871C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
74171E631C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
74B4AD211D09A6190062A523 /* SSLSecurity.swift in Sources */,
74171EBD1C10CD240062D398 /* SocketStringReader.swift in Sources */,
74171EC31C10CD240062D398 /* SocketTypes.swift in Sources */,
74171EAB1C10CD240062D398 /* SocketLogger.swift in Sources */,
74171E991C10CD240062D398 /* SocketIOClient.swift in Sources */,
749642B81D3FCE5500DD32D1 /* WebSocket.swift in Sources */,
74171E8D1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7B1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171EB11C10CD240062D398 /* SocketPacket.swift in Sources */,
749642B51D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */,
74171EB71C10CD240062D398 /* SocketParsable.swift in Sources */,
74171E811C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171E6F1C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
747BC5991D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */,
74171E9F1C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
74BC45AB1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
);
@@ -646,25 +655,9 @@
buildActionMask = 2147483647;
files = (
7472C65F1BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
74171EA61C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E881C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
74171EA01C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
74171E701C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
74171EC41C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E8E1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7C1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E821C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171EB21C10CD240062D398 /* SocketPacket.swift in Sources */,
741F39EE1BD025D80026C9CC /* SocketEngineTest.swift in Sources */,
74171EBE1C10CD240062D398 /* SocketStringReader.swift in Sources */,
74F124F01BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */,
74171E6A1C10CD240062D398 /* SocketAckManager.swift in Sources */,
74171E761C10CD240062D398 /* SocketEngine.swift in Sources */,
74171E641C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
74171EB81C10CD240062D398 /* SocketParsable.swift in Sources */,
74171EAC1C10CD240062D398 /* SocketLogger.swift in Sources */,
7472C65C1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */,
74171E9A1C10CD240062D398 /* SocketIOClient.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -672,14 +665,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74B4AD241D09A6450062A523 /* WebSocket.swift in Sources */,
740CA1211C496EF200CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEA1C39926300364B59 /* SocketIOClientSpec.swift in Sources */,
CEBA569B1CDA0B8200BA0389 /* String.swift in Sources */,
CEBA569B1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */,
74171EA71C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E771C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7A1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
CEBA56971CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
74171E6B1C10CD240062D398 /* SocketAckManager.swift in Sources */,
74171E891C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
74171E651C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
@@ -687,13 +678,15 @@
74171EC51C10CD240062D398 /* SocketTypes.swift in Sources */,
74171EAD1C10CD240062D398 /* SocketLogger.swift in Sources */,
74171E9B1C10CD240062D398 /* SocketIOClient.swift in Sources */,
749642B91D3FCE5500DD32D1 /* WebSocket.swift in Sources */,
74171E8F1C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7D1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74B4AD221D09A6190062A523 /* SSLSecurity.swift in Sources */,
74171EB31C10CD240062D398 /* SocketPacket.swift in Sources */,
749642B61D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */,
74171EB91C10CD240062D398 /* SocketParsable.swift in Sources */,
74171E831C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171E711C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
747BC59A1D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */,
74171EA11C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
74BC45AC1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
);
@@ -706,8 +699,8 @@
742D150C1CA5794B00BD987D /* SocketObjectiveCTest.m in Sources */,
74321DCB1C2D939A00CF6F43 /* SocketAckManagerTest.swift in Sources */,
74321DCC1C2D939A00CF6F43 /* SocketParserTest.swift in Sources */,
747BC59F1D5F9BA200CA5FA4 /* SocketIOClientConfigurationTest.swift in Sources */,
7472C6601BCAC46E003CA70D /* SocketSideEffectTest.swift in Sources */,
74171EA81C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
741F39EF1BD025D80026C9CC /* SocketEngineTest.swift in Sources */,
74F124F11BC574CF002966F4 /* SocketBasicPacketTest.swift in Sources */,
7472C65D1BCAB53E003CA70D /* SocketNamespacePacketTest.swift in Sources */,
@@ -718,14 +711,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74B4AD251D09A6490062A523 /* WebSocket.swift in Sources */,
740CA1201C496EEB00CB98F4 /* SocketEngineWebsocket.swift in Sources */,
7471CCEB1C39926C00364B59 /* SocketIOClientSpec.swift in Sources */,
CEBA569C1CDA0B8200BA0389 /* String.swift in Sources */,
CEBA569C1CDA0B8200BA0389 /* SocketExtensions.swift in Sources */,
74171EA91C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E791C10CD240062D398 /* SocketEngine.swift in Sources */,
7420CB7B1C49629E00956AA4 /* SocketEnginePollable.swift in Sources */,
CEBA56981CDA0B7700BA0389 /* NSCharacterSet.swift in Sources */,
74171E6D1C10CD240062D398 /* SocketAckManager.swift in Sources */,
74171E8B1C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
74171E671C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
@@ -733,13 +724,15 @@
74171EC71C10CD240062D398 /* SocketTypes.swift in Sources */,
74171EAF1C10CD240062D398 /* SocketLogger.swift in Sources */,
74171E9D1C10CD240062D398 /* SocketIOClient.swift in Sources */,
749642BA1D3FCE5500DD32D1 /* WebSocket.swift in Sources */,
74171E911C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E7F1C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74B4AD231D09A6190062A523 /* SSLSecurity.swift in Sources */,
74171EB51C10CD240062D398 /* SocketPacket.swift in Sources */,
749642B71D3FCE5500DD32D1 /* SSLSecurity.swift in Sources */,
74171EBB1C10CD240062D398 /* SocketParsable.swift in Sources */,
74171E851C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171E731C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
747BC59B1D5F943500CA5FA4 /* SocketIOClientConfiguration.swift in Sources */,
74171EA31C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
74BC45AD1D0C6675008CC431 /* SocketClientManager.swift in Sources */,
);
@@ -750,25 +743,9 @@
buildActionMask = 2147483647;
files = (
57634A231BD9B46D00E19CD7 /* SocketSideEffectTest.swift in Sources */,
74171EAA1C10CD240062D398 /* SocketIOClientStatus.swift in Sources */,
74171E8C1C10CD240062D398 /* SocketEngineSpec.swift in Sources */,
74171EA41C10CD240062D398 /* SocketIOClientOption.swift in Sources */,
74171E741C10CD240062D398 /* SocketAnyEvent.swift in Sources */,
74171EC81C10CD240062D398 /* SocketTypes.swift in Sources */,
74171E921C10CD240062D398 /* SocketEventHandler.swift in Sources */,
74171E801C10CD240062D398 /* SocketEngineClient.swift in Sources */,
74171E861C10CD240062D398 /* SocketEnginePacketType.swift in Sources */,
74171EB61C10CD240062D398 /* SocketPacket.swift in Sources */,
57634A2A1BD9B46D00E19CD7 /* SocketEngineTest.swift in Sources */,
74171EC21C10CD240062D398 /* SocketStringReader.swift in Sources */,
57634A2F1BD9B46D00E19CD7 /* SocketBasicPacketTest.swift in Sources */,
74171E6E1C10CD240062D398 /* SocketAckManager.swift in Sources */,
74171E7A1C10CD240062D398 /* SocketEngine.swift in Sources */,
74171E681C10CD240062D398 /* SocketAckEmitter.swift in Sources */,
74171EBC1C10CD240062D398 /* SocketParsable.swift in Sources */,
74171EB01C10CD240062D398 /* SocketLogger.swift in Sources */,
57634A321BD9B46D00E19CD7 /* SocketNamespacePacketTest.swift in Sources */,
74171E9E1C10CD240062D398 /* SocketIOClient.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -797,15 +774,31 @@
isa = XCBuildConfiguration;
buildSettings = {
BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application";
ENABLE_BITCODE = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
ONLY_ACTIVE_ARCH = YES;
PRODUCT_NAME = SocketIOClientSwift;
PRODUCT_NAME = SocketIO;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
@@ -815,12 +808,28 @@
isa = XCBuildConfiguration;
buildSettings = {
BITCODE_GENERATION_MODE = bitcode;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "Developer ID Application";
ENABLE_BITCODE = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MACOSX_DEPLOYMENT_TARGET = 10.10;
PRODUCT_NAME = SocketIOClientSwift;
PRODUCT_NAME = SocketIO;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 3.0;
TVOS_DEPLOYMENT_TARGET = 9.0;
WATCHOS_DEPLOYMENT_TARGET = 2.0;
};
@@ -830,6 +839,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
@@ -876,6 +886,7 @@
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@@ -886,6 +897,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
APPLICATION_EXTENSION_API_ONLY = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
@@ -925,6 +937,7 @@
PRODUCT_BUNDLE_IDENTIFIER = io.socket.SocketIOClientSwift;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
@@ -972,7 +985,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
INFOPLIST_FILE = "SocketIO-iOSTests/Info.plist";
INFOPLIST_FILE = "SocketIO-iOS/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = YES;
@@ -1017,7 +1030,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
INFOPLIST_FILE = "SocketIO-iOSTests/Info.plist";
INFOPLIST_FILE = "SocketIO-iOS/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = NO;
@@ -1081,6 +1094,7 @@
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
@@ -1132,6 +1146,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
SDKROOT = macosx;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
@@ -1188,6 +1203,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
@@ -1234,6 +1250,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "io.socket.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_VERSION = 3.0;
};
name = Release;
};
@@ -1387,7 +1404,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
INFOPLIST_FILE = "SocketIO-iOSTests/Info.plist";
INFOPLIST_FILE = "SocketIO-iOS/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = YES;
@@ -1432,7 +1449,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
INFOPLIST_FILE = "SocketIO-iOSTests/Info.plist";
INFOPLIST_FILE = "SocketIO-iOS/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MTL_ENABLE_DEBUG_INFO = NO;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0720"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -57,7 +57,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -79,7 +79,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -97,7 +97,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0720"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -58,7 +58,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -80,7 +80,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -98,7 +98,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIOClientSwift.framework"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0720"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+6 -6
View File
@@ -7,20 +7,20 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager()
func testAddAcks() {
let callbackExpection = self.expectationWithDescription("callbackExpection")
let callbackExpection = self.expectation(description: "callbackExpection")
let itemsArray = ["Hi", "ho"]
func callback(items: [AnyObject]) {
func callback(_ items: [Any]) {
callbackExpection.fulfill()
}
ackManager.addAck(1, callback: callback)
ackManager.executeAck(1, items: itemsArray)
waitForExpectationsWithTimeout(3.0, handler: nil)
ackManager.executeAck(1, with: itemsArray, onQueue: DispatchQueue.main)
waitForExpectations(timeout: 3.0, handler: nil)
}
}
+25 -23
View File
@@ -7,11 +7,11 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketBasicPacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
func testEmpyEmit() {
let expectedSendString = "2[\"test\"]"
@@ -23,7 +23,7 @@ class SocketBasicPacketTest: XCTestCase {
func testNullEmit() {
let expectedSendString = "2[\"test\",null]"
let sendData = ["test", NSNull()]
let sendData: [Any] = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -46,8 +46,8 @@ class SocketBasicPacketTest: XCTestCase {
}
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()]]
let expectedSendString = "2[\"test\",{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let sendData: [Any] = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -55,15 +55,15 @@ class SocketBasicPacketTest: XCTestCase {
func testArrayEmit() {
let expectedSendString = "2[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
let sendData = ["test", ["hello", 1, ["test": "test"]]]
let sendData: [Any] = ["test", ["hello", 1, ["test": "test"]]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let expectedSendString = "51-[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -71,12 +71,12 @@ class SocketBasicPacketTest: XCTestCase {
}
func testMultipleBinaryEmit() {
let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let expectedSendString = "52-[\"test\",{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData: [Any] = ["test", ["data1": data, "data2": data2] as NSDictionary]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data, data2])
XCTAssertEqual(packet.binary, [data2, data])
}
func testEmitWithAck() {
@@ -84,12 +84,14 @@ class SocketBasicPacketTest: XCTestCase {
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.packetString,
expectedSendString)
}
func testEmitDataWithAck() {
let expectedSendString = "51-0[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let expectedSendString = "51-0[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -121,7 +123,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testJSONAck() {
let expectedSendString = "30[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let expectedSendString = "30[{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -129,7 +131,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testBinaryAck() {
let expectedSendString = "61-0[{\"num\":0,\"_placeholder\":true}]"
let expectedSendString = "61-0[{\"_placeholder\":true,\"num\":0}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -138,7 +140,7 @@ class SocketBasicPacketTest: XCTestCase {
}
func testMultipleBinaryAck() {
let expectedSendString = "62-0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
let expectedSendString = "62-0[{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData = [["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
@@ -147,15 +149,15 @@ class SocketBasicPacketTest: XCTestCase {
}
func testBinaryStringPlaceholderInMessage() {
let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"num\":1,\"_placeholder\":true}]"
let socket = SocketIOClient(socketURL: NSURL())
let engineString = "52-[\"test\",\"~~0\",{\"num\":0,\"_placeholder\":true},{\"_placeholder\":true,\"num\":1}]"
let socket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
socket.setTestable()
if case let .Right(packet) = socket.parseString(engineString) {
if case let .right(packet) = socket.parseString(engineString) {
var packet = packet
XCTAssertEqual(packet.event, "test")
packet.addData(data)
packet.addData(data2)
_ = packet.addData(data)
_ = packet.addData(data2)
XCTAssertEqual(packet.args[0] as? String, "~~0")
} else {
XCTFail()
+36 -17
View File
@@ -7,7 +7,7 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketEngineTest: XCTestCase {
var client: SocketIOClient!
@@ -15,24 +15,24 @@ class SocketEngineTest: XCTestCase {
override func setUp() {
super.setUp()
client = SocketIOClient(socketURL: NSURL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: NSURL(string: "http://localhost")!, options: nil)
client = SocketIOClient(socketURL: URL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: URL(string: "http://localhost")!, options: nil)
client.setTestable()
}
func testBasicPollingMessage() {
let expectation = expectationWithDescription("Basic polling test")
let expect = expectation(description: "Basic polling test")
client.on("blankTest") {data, ack in
expectation.fulfill()
expect.fulfill()
}
engine.parsePollingMessage("15:42[\"blankTest\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testTwoPacketsInOnePollTest() {
let finalExpectation = expectationWithDescription("Final packet in poll test")
let finalExpectation = expectation(description: "Final packet in poll test")
var gotBlank = false
client.on("blankTest") {data, ack in
@@ -40,7 +40,7 @@ class SocketEngineTest: XCTestCase {
}
client.on("stringTest") {data, ack in
if let str = data[0] as? String where gotBlank {
if let str = data[0] as? String, gotBlank {
if str == "hello" {
finalExpectation.fulfill()
}
@@ -48,43 +48,43 @@ class SocketEngineTest: XCTestCase {
}
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDoesErrorOnUnknownTransport() {
let finalExpectation = expectationWithDescription("Unknown Transport")
let finalExpectation = expectation(description: "Unknown Transport")
client.on("error") {data, ack in
if let error = data[0] as? String where error == "Unknown transport" {
if let error = data[0] as? String, error == "Unknown transport" {
finalExpectation.fulfill()
}
}
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDoesErrorOnUnknownMessage() {
let finalExpectation = expectationWithDescription("Engine Errors")
let finalExpectation = expectation(description: "Engine Errors")
client.on("error") {data, ack in
finalExpectation.fulfill()
}
engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDecodesUTF8Properly() {
let expectation = expectationWithDescription("Engine Decodes utf8")
let expect = expectation(description: "Engine Decodes utf8")
client.on("stringTest") {data, ack in
XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test")
expectation.fulfill()
expect.fulfill()
}
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testEncodeURLProperly() {
@@ -102,4 +102,23 @@ class SocketEngineTest: XCTestCase {
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D")
}
func testBase64Data() {
let expect = expectation(description: "Engine Decodes base64 data")
let b64String = "b4aGVsbG8NCg=="
let packetString = "451-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]"
client.on("test") {data, ack in
if let data = data[0] as? Data, let string = String(data: data, encoding: .utf8) {
XCTAssertEqual(string, "hello")
}
expect.fulfill()
}
engine.parseEngineMessage(packetString, fromPolling: false)
engine.parseEngineMessage(b64String, fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
}
}
@@ -0,0 +1,46 @@
//
// TestSocketIOClientConfiguration.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 8/13/16.
//
//
import XCTest
import SocketIO
class TestSocketIOClientConfiguration: XCTestCase {
var config = [] as SocketIOClientConfiguration
override func setUp() {
super.setUp()
config = [.log(false), .forceNew(true)]
}
func testReplaceSameOption() {
config.insert(.log(true))
XCTAssertEqual(config.count, 2)
switch config[0] {
case let .log(log):
XCTAssertTrue(log)
default:
XCTFail()
}
}
func testIgnoreIfExisting() {
config.insert(.forceNew(false), replacing: false)
XCTAssertEqual(config.count, 2)
switch config[1] {
case let .forceNew(new):
XCTAssertTrue(new)
default:
XCTFail()
}
}
}
@@ -7,15 +7,15 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketNamespacePacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
func testEmpyEmit() {
let expectedSendString = "2/swift,[\"test\"]"
let sendData = ["test"]
let sendData: [Any] = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -23,7 +23,7 @@ class SocketNamespacePacketTest: XCTestCase {
func testNullEmit() {
let expectedSendString = "2/swift,[\"test\",null]"
let sendData = ["test", NSNull()]
let sendData: [Any] = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -31,31 +31,32 @@ class SocketNamespacePacketTest: XCTestCase {
func testStringEmit() {
let expectedSendString = "2/swift,[\"test\",\"foo bar\"]"
let sendData = ["test", "foo bar"]
let sendData: [Any] = ["test", "foo bar"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2/swift,[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let expectedSendString = "2/swift,[\"test\",{\"null\":null,\"test\":\"hello\",\"hello\":1,\"foobar\":true}]"
let sendData: [Any] = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()] as NSDictionary]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testArrayEmit() {
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
let sendData = ["test", ["hello", 1, ["test": "test"]]]
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"},true]]"
let sendData: [Any] = ["test", ["hello", 1, ["test": "test"], true]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-/swift,[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let expectedSendString = "51-/swift,[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -63,12 +64,12 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testMultipleBinaryEmit() {
let expectedSendString = "52-/swift,[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let expectedSendString = "52-/swift,[\"test\",{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData: [Any] = ["test", ["data1": data, "data2": data2] as NSDictionary]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data, data2])
XCTAssertEqual(packet.binary, [data2, data])
}
func testEmitWithAck() {
@@ -80,8 +81,8 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testEmitDataWithAck() {
let expectedSendString = "51-/swift,0[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let expectedSendString = "51-/swift,0[\"test\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
@@ -113,7 +114,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testJSONAck() {
let expectedSendString = "3/swift,0[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let expectedSendString = "3/swift,0[{\"null\":null,\"hello\":1,\"test\":\"hello\",\"foobar\":true}]"
let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
@@ -121,7 +122,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testBinaryAck() {
let expectedSendString = "61-/swift,0[{\"num\":0,\"_placeholder\":true}]"
let expectedSendString = "61-/swift,0[{\"_placeholder\":true,\"num\":0}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
@@ -130,7 +131,7 @@ class SocketNamespacePacketTest: XCTestCase {
}
func testMultipleBinaryAck() {
let expectedSendString = "62-/swift,0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
let expectedSendString = "62-/swift,0[{\"data2\":{\"_placeholder\":true,\"num\":0},\"data1\":{\"_placeholder\":true,\"num\":1}}]"
let sendData = [["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
+6 -6
View File
@@ -8,7 +8,7 @@
//
#import <XCTest/XCTest.h>
@import SocketIOClientSwift;
@import SocketIO;
@interface SocketObjectiveCTest : XCTestCase
@@ -21,7 +21,7 @@
- (void)setUp {
[super setUp];
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
self.socket = [[SocketIOClient alloc] initWithSocketURL:url options:nil];
self.socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
}
- (void)testOnSyntax {
@@ -31,13 +31,13 @@
}
- (void)testEmitSyntax {
[self.socket emit:@"testEmit" withItems:@[@YES]];
[self.socket emit:@"testEmit" with:@[@YES]];
}
- (void)testEmitWithAckSyntax {
[self.socket emitWithAck:@"testAckEmit" withItems:@[@YES]](0, ^(NSArray* data) {
[[self.socket emitWithAck:@"testAckEmit" with:@[@YES]] timingOutAfter:0 callback:^(NSArray* data) {
});
}];
}
- (void)testOffSyntax {
@@ -47,7 +47,7 @@
- (void)testSocketManager {
SocketClientManager* manager = [SocketClientManager sharedManager];
[manager addSocket:self.socket labeledAs:@"test"];
[manager removeSocketWithLabel:@"test"];
[manager removeSocketWithLabel:@"test"];
}
@end
+27 -21
View File
@@ -7,27 +7,28 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketParserTest: XCTestCase {
let testSocket = SocketIOClient(socketURL: NSURL())
let testSocket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
//Format key: message; namespace-data-binary-id
static let packetTypes: [String: (String, [AnyObject], [NSData], Int)] = [
static let packetTypes: [String: (String, [Any], [Data], Int)] = [
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
"25[\"test\"]": ("/", ["test"], [], 5),
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"] as NSArray], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2] as NSArray, ["test": "bob"] as NSDictionary, 25, "polo", ["_placeholder": true, "num": 0] as NSDictionary], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"] as NSArray], [], 0),
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]":
("/swift", [ [1, 2], ["test": "bob"], 25, "polo", ["_placeholder": true, "num": 0]], [], 19),
("/swift", [ [1, 2] as NSArray, ["test": "bob"] as NSDictionary, 25, "polo", ["_placeholder": true, "num": 0] as NSDictionary], [], 19),
"4/swift,": ("/swift", [], [], -1),
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"4{\"test\":2}": ("/", [["test": 2]], [], -1),
"41": ("/", [1], [], -1)]
"41": ("/", [1], [], -1),
"4[1, \"hello\"]": ("/", [1, "hello"], [], -1)]
func testDisconnect() {
let message = "1"
@@ -99,33 +100,38 @@ class SocketParserTest: XCTestCase {
validateParseResult(message)
}
func testErrorTypeArray() {
let message = "4[1, \"hello\"]"
validateParseResult(message)
}
func testInvalidInput() {
let message = "8"
switch testSocket.parseString(message) {
case .Left(_):
case .left(_):
return
case .Right(_):
case .right(_):
XCTFail("Created packet when shouldn't have")
}
}
func testGenericParser() {
var parser = SocketStringReader(message: "61-/swift,")
XCTAssertEqual(parser.read(1), "6")
XCTAssertEqual(parser.read(count: 1), "6")
XCTAssertEqual(parser.currentCharacter, "1")
XCTAssertEqual(parser.readUntilStringOccurence("-"), "1")
XCTAssertEqual(parser.readUntilOccurence(of: "-"), "1")
XCTAssertEqual(parser.currentCharacter, "/")
}
func validateParseResult(message: String) {
func validateParseResult(_ message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = testSocket.parseString(message)
let type = message.substringWithRange(Range<String.Index>(message.startIndex..<message.startIndex.advancedBy(1)))
if case let .Right(packet) = packet {
let type = String(message.characters.prefix(1))
if case let .right(packet) = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
XCTAssertEqual(packet.nsp, validValues.0)
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1), "\(packet.data)")
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2), "\(packet.binary)")
XCTAssertTrue((packet.data as NSArray).isEqual(to: validValues.1), "\(packet.data)")
XCTAssertTrue((packet.binary as NSArray).isEqual(to: validValues.2), "\(packet.binary)")
XCTAssertEqual(packet.id, validValues.3)
} else {
XCTFail()
@@ -134,10 +140,10 @@ class SocketParserTest: XCTestCase {
func testParsePerformance() {
let keys = Array(SocketParserTest.packetTypes.keys)
measureBlock({
for item in keys.enumerate() {
self.testSocket.parseString(item.element)
measure {
for item in keys.enumerated() {
_ = self.testSocket.parseString(item.element)
}
})
}
}
}
+41 -41
View File
@@ -7,16 +7,16 @@
//
import XCTest
@testable import SocketIOClientSwift
@testable import SocketIO
class SocketSideEffectTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
private var socket: SocketIOClient!
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: NSURL())
socket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
socket.setTestable()
}
@@ -25,72 +25,72 @@ class SocketSideEffectTest: XCTestCase {
}
func testFirstAck() {
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
socket.emitWithAck("test").timingOut(after: 0) {data in}
XCTAssertEqual(socket.currentAck, 0)
}
func testSecondAck() {
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
socket.emitWithAck("test").timingOut(after: 0) {data in}
socket.emitWithAck("test").timingOut(after: 0) {data in}
XCTAssertEqual(socket.currentAck, 1)
}
func testHandleAck() {
let expectation = expectationWithDescription("handled ack")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
let expect = expectation(description: "handled ack")
socket.emitWithAck("test").timingOut(after: 0) {data in
XCTAssertEqual(data[0] as? String, "hello world")
expectation.fulfill()
expect.fulfill()
}
socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleAck2() {
let expectation = expectationWithDescription("handled ack2")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
let expect = expectation(description: "handled ack2")
socket.emitWithAck("test").timingOut(after: 0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expectation.fulfill()
expect.fulfill()
}
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(NSData())
waitForExpectationsWithTimeout(3, handler: nil)
socket.parseBinaryData(Data())
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleEvent() {
let expectation = expectationWithDescription("handled event")
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
expectation.fulfill()
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expectation = expectationWithDescription("handled event")
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expectation.fulfill()
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleOnceEvent() {
let expectation = expectationWithDescription("handled event")
let expect = expectation(description: "handled event")
socket.once("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
XCTAssertEqual(self.socket.testHandlers.count, 0)
expectation.fulfill()
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testOffWithEvent() {
@@ -112,46 +112,46 @@ class SocketSideEffectTest: XCTestCase {
}
func testHandlesErrorPacket() {
let expectation = expectationWithDescription("Handled error")
let expect = expectation(description: "Handled error")
socket.on("error") {data, ack in
if let error = data[0] as? String where error == "test error" {
expectation.fulfill()
if let error = data[0] as? String, error == "test error" {
expect.fulfill()
}
}
socket.parseSocketMessage("4\"test error\"")
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleBinaryEvent() {
let expectation = expectationWithDescription("handled binary event")
let expect = expectation(description: "handled binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData {
XCTAssertEqual(data, self.data)
expectation.fulfill()
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData {
XCTAssertEqual(data as Data, self.data)
expect.fulfill()
}
}
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
socket.parseBinaryData(data)
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleMultipleBinaryEvent() {
let expectation = expectationWithDescription("handled multiple binary event")
let expect = expectation(description: "handled multiple binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData,
data2 = dict["test2"] as? NSData {
XCTAssertEqual(data, self.data)
XCTAssertEqual(data2, self.data2)
expectation.fulfill()
if let dict = data[0] as? NSDictionary, let data = dict["test"] as? NSData,
let data2 = dict["test2"] as? NSData {
XCTAssertEqual(data as Data, self.data)
XCTAssertEqual(data2 as Data, self.data2)
expect.fulfill()
}
}
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
socket.parseBinaryData(data)
socket.parseBinaryData(data2)
waitForExpectationsWithTimeout(3, handler: nil)
waitForExpectations(timeout: 3, handler: nil)
}
func testSocketManager() {
File renamed without changes.
-31
View File
@@ -1,31 +0,0 @@
//
// NSCharacterSet.swift
// Socket.IO-Client-Swift
//
// Created by Yannick Loriot on 5/4/16.
//
// 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
extension NSCharacterSet {
class var allowedURLCharacterSet: NSCharacterSet {
return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
}
}
@@ -4,7 +4,7 @@
// Starscream
//
// Created by Dalton Cherry on 5/16/15.
// Copyright (c) 2014-2015 Dalton Cherry.
// Copyright (c) 2014-2016 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -19,13 +19,16 @@
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import Security
public class SSLCert : NSObject {
var certData: NSData?
var key: SecKeyRef?
public protocol SSLTrustValidator {
func isValid(_ trust: SecTrust, domain: String?) -> Bool
}
open class SSLCert : NSObject {
var certData: Data?
var key: SecKey?
/**
Designated init for certificates
@@ -34,7 +37,7 @@ public class SSLCert : NSObject {
- returns: a representation security object to be used with
*/
public init(data: NSData) {
public init(data: Data) {
self.certData = data
}
@@ -45,17 +48,17 @@ public class SSLCert : NSObject {
- returns: a representation security object to be used with
*/
public init(key: SecKeyRef) {
public init(key: SecKey) {
self.key = key
}
}
public class SSLSecurity : NSObject {
open class SSLSecurity : SSLTrustValidator {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
var pubKeys: [SecKeyRef]? //the public keys
var certificates: [Data]? //the certificates
@nonobjc var pubKeys: [SecKey]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
@@ -66,12 +69,12 @@ public class SSLSecurity : NSObject {
- returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
let paths = Bundle.main.paths(forResourcesOfType: "cer", inDirectory: ".")
let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in
var certs = certs
if let data = NSData(contentsOfFile: path) {
certs.append(SSLCert(data: data))
certs.append(SSLCert(data: data as Data))
}
return certs
}
@@ -82,21 +85,19 @@ public class SSLSecurity : NSObject {
/**
Designated init
- parameter keys: is the certificates or public keys to use
- parameter certs: is the certificates or public keys to use
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public init(certs: [SSLCert], usePublicKeys: Bool) {
super.init()
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
DispatchQueue.global(qos: .default).async {
let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in
var pubKeys = pubKeys
if let data = cert.certData where cert.key == nil {
if let data = cert.certData, cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let key = cert.key {
@@ -109,7 +110,7 @@ public class SSLSecurity : NSObject {
self.isReady = true
}
} else {
let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in
let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
@@ -129,26 +130,26 @@ public class SSLSecurity : NSObject {
- returns: if the key was successfully validated
*/
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
public func isValid(_ trust: SecTrust, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
while !self.isReady {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
var policy: SecPolicy
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain)
policy = SecPolicyCreateSSL(true, domain as NSString?)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
let serverPubKeys = publicKeyChainForTrust(trust)
let serverPubKeys = publicKeyChain(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
@@ -158,16 +159,15 @@ public class SSLSecurity : NSObject {
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
let serverCerts = certificateChain(trust)
var collect = [SecCertificate]()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert)!)
collect.append(SecCertificateCreateWithData(nil,cert as CFData)!)
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustSetAnchorCertificates(trust,collect as NSArray)
var result: SecTrustResultType = .unspecified
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
if result == .unspecified || result == .proceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
@@ -192,10 +192,10 @@ public class SSLSecurity : NSObject {
- returns: a public key
*/
func extractPublicKey(data: NSData) -> SecKeyRef? {
guard let cert = SecCertificateCreateWithData(nil, data) else { return nil }
func extractPublicKey(_ data: Data) -> SecKey? {
guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil }
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
return extractPublicKey(cert, policy: SecPolicyCreateBasicX509())
}
/**
@@ -205,13 +205,12 @@ public class SSLSecurity : NSObject {
- returns: a public key
*/
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? {
var possibleTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
guard let trust = possibleTrust else { return nil }
var result: SecTrustResultType = 0
var result: SecTrustResultType = .unspecified
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
@@ -223,11 +222,11 @@ public class SSLSecurity : NSObject {
- returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> [NSData] {
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in
func certificateChain(_ trust: SecTrust) -> [Data] {
let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([Data]()) { (certificates: [Data], index: Int) -> [Data] in
var certificates = certificates
let cert = SecTrustGetCertificateAtIndex(trust, index)
certificates.append(SecCertificateCopyData(cert!))
certificates.append(SecCertificateCopyData(cert!) as Data)
return certificates
}
@@ -241,12 +240,12 @@ public class SSLSecurity : NSObject {
- returns: the public keys from the certifcate chain for the trust
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] {
@nonobjc func publicKeyChain(_ trust: SecTrust) -> [SecKey] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [SecKey] in
var keys = keys
let cert = SecTrustGetCertificateAtIndex(trust, index)
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
if let key = extractPublicKey(cert!, policy: policy) {
keys.append(key)
}
@@ -257,4 +256,4 @@ public class SSLSecurity : NSObject {
}
}
}
+44 -4
View File
@@ -27,21 +27,61 @@ import Foundation
public final class SocketAckEmitter : NSObject {
let socket: SocketIOClient
let ackNum: Int
public var expected: Bool {
return ackNum != -1
}
init(socket: SocketIOClient, ackNum: Int) {
self.socket = socket
self.ackNum = ackNum
}
public func with(items: AnyObject...) {
public func with(_ items: SocketData...) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, withItems: items)
socket.emitAck(ackNum, with: items)
}
public func with(items: [AnyObject]) {
public func with(_ items: [Any]) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, withItems: items)
socket.emitAck(ackNum, with: items)
}
}
public final class OnAckCallback : NSObject {
private let ackNumber: Int
private let items: [Any]
private weak var socket: SocketIOClient?
init(ackNumber: Int, items: [Any], socket: SocketIOClient) {
self.ackNumber = ackNumber
self.items = items
self.socket = socket
}
deinit {
DefaultSocketLogger.Logger.log("OnAckCallback for \(ackNumber) being released", type: "OnAckCallback")
}
public func timingOut(after seconds: Int, callback: @escaping AckCallback) {
guard let socket = self.socket else { return }
socket.ackQueue.sync() {
socket.ackHandlers.addAck(ackNumber, callback: callback)
}
socket._emit(items, ack: ackNumber)
guard seconds != 0 else { return }
let time = DispatchTime.now() + Double(UInt64(seconds) * NSEC_PER_SEC) / Double(NSEC_PER_SEC)
socket.handleQueue.asyncAfter(deadline: time) {
socket.ackHandlers.timeoutAck(self.ackNumber, onQueue: socket.handleQueue)
}
}
}
+18 -13
View File
@@ -24,7 +24,7 @@
import Foundation
private struct SocketAck : Hashable, Equatable {
private struct SocketAck : Hashable {
let ack: Int
var callback: AckCallback!
var hashValue: Int {
@@ -35,7 +35,7 @@ private struct SocketAck : Hashable, Equatable {
self.ack = ack
}
init(ack: Int, callback: AckCallback) {
init(ack: Int, callback: @escaping AckCallback) {
self.ack = ack
self.callback = callback
}
@@ -51,24 +51,29 @@ private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
struct SocketAckManager {
private var acks = Set<SocketAck>(minimumCapacity: 1)
private let ackSemaphore = DispatchSemaphore(value: 1)
mutating func addAck(ack: Int, callback: AckCallback) {
mutating func addAck(_ ack: Int, callback: @escaping AckCallback) {
acks.insert(SocketAck(ack: ack, callback: callback))
}
mutating func executeAck(ack: Int, items: [AnyObject]) {
let callback = acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(items)
}
/// Should be called on handle queue
mutating func executeAck(_ ack: Int, with items: [Any], onQueue: DispatchQueue) {
ackSemaphore.wait()
defer { ackSemaphore.signal() }
let ack = acks.remove(SocketAck(ack: ack))
onQueue.async() { ack?.callback(items) }
}
mutating func timeoutAck(ack: Int) {
let callback = acks.remove(SocketAck(ack: ack))
/// Should be called on handle queue
mutating func timeoutAck(_ ack: Int, onQueue: DispatchQueue) {
ackSemaphore.wait()
defer { ackSemaphore.signal() }
let ack = acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(["NO ACK"])
onQueue.async() {
ack?.callback?(["NO ACK"])
}
}
}
+3 -3
View File
@@ -26,12 +26,12 @@ import Foundation
public final class SocketAnyEvent : NSObject {
public let event: String
public let items: NSArray?
public let items: [Any]?
override public var description: String {
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
return "SocketAnyEvent: Event: \(event) items: \(String(describing: items))"
}
init(event: String, items: NSArray?) {
init(event: String, items: [Any]?) {
self.event = event
self.items = items
}
+9 -9
View File
@@ -43,12 +43,12 @@ import Foundation
manager["room1"]?.emit("hello")
```
*/
public final class SocketClientManager : NSObject {
public static let sharedManager = SocketClientManager()
open class SocketClientManager : NSObject {
open static let sharedManager = SocketClientManager()
private var sockets = [String: SocketIOClient]()
public subscript(string: String) -> SocketIOClient? {
open subscript(string: String) -> SocketIOClient? {
get {
return sockets[string]
}
@@ -58,25 +58,25 @@ public final class SocketClientManager : NSObject {
}
}
public func addSocket(socket: SocketIOClient, labeledAs label: String) {
open func addSocket(_ socket: SocketIOClient, labeledAs label: String) {
sockets[label] = socket
}
public func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValueForKey(label)
open func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValue(forKey: label)
}
public func removeSocket(socket socket: SocketIOClient) -> SocketIOClient? {
open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? {
var returnSocket: SocketIOClient?
for (label, dictSocket) in sockets where dictSocket === socket {
returnSocket = sockets.removeValueForKey(label)
returnSocket = sockets.removeValue(forKey: label)
}
return returnSocket
}
public func removeSockets() {
open func removeSockets() {
sockets.removeAll()
}
}
+219 -215
View File
@@ -24,24 +24,24 @@
import Foundation
public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = DispatchQueue(label: "com.socketio.engineEmitQueue", attributes: [])
public let handleQueue = DispatchQueue(label: "com.socketio.engineHandleQueue", attributes: [])
public let parseQueue = DispatchQueue(label: "com.socketio.engineParseQueue", attributes: [])
public var connectParams: [String: AnyObject]? {
public var connectParams: [String: Any]? {
didSet {
(urlPolling, urlWebSocket) = createURLs()
}
}
public var postWait = [String]()
public var waitingForPoll = false
public var waitingForPost = false
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var cookies: [HTTPCookie]?
public private(set) var doubleEncodeUTF8 = true
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
@@ -50,28 +50,28 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
public private(set) var invalidated = false
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: NSURLSession?
public private(set) var session: URLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io/"
public private(set) var urlPolling = NSURL()
public private(set) var urlWebSocket = NSURL()
public private(set) var urlPolling = URL(string: "http://localhost/")!
public private(set) var urlWebSocket = URL(string: "http://localhost/")!
public private(set) var websocket = false
public private(set) var ws: WebSocket?
public weak var client: SocketEngineClient?
private weak var sessionDelegate: NSURLSessionDelegate?
private weak var sessionDelegate: URLSessionDelegate?
private let logType = "SocketEngine"
private let url: NSURL
private let url: URL
private var pingInterval: Double?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var probeWait = ProbeWaitQueue()
@@ -80,147 +80,140 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
private var selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: NSURL, options: Set<SocketIOClientOption>) {
public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) {
self.client = client
self.url = url
for option in options {
for option in config {
switch option {
case let .ConnectParams(params):
case let .connectParams(params):
connectParams = params
case let .Cookies(cookies):
case let .cookies(cookies):
self.cookies = cookies
case let .DoubleEncodeUTF8(encode):
case let .doubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .ExtraHeaders(headers):
case let .extraHeaders(headers):
extraHeaders = headers
case let .SessionDelegate(delegate):
case let .sessionDelegate(delegate):
sessionDelegate = delegate
case let .ForcePolling(force):
case let .forcePolling(force):
forcePolling = force
case let .ForceWebsockets(force):
case let .forceWebsockets(force):
forceWebsockets = force
case let .Path(path):
case let .path(path):
socketPath = path
case let .VoipEnabled(enable):
if !socketPath.hasSuffix("/") {
socketPath += "/"
}
case let .voipEnabled(enable):
voipEnabled = enable
case let .Secure(secure):
case let .secure(secure):
self.secure = secure
case let .Security(security):
self.security = security
case let .SelfSigned(selfSigned):
case let .selfSigned(selfSigned):
self.selfSigned = selfSigned
case let .security(security):
self.security = security
default:
continue
}
}
super.init()
sessionDelegate = sessionDelegate ?? self
(urlPolling, urlWebSocket) = createURLs()
}
public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) {
self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? [])
public convenience init(client: SocketEngineClient, url: URL, options: NSDictionary?) {
self.init(client: client, url: url, config: options?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
private func checkAndHandleEngineError(msg: String) {
guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false) else { return }
private func checkAndHandleEngineError(_ msg: String) {
do {
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: .MutableContainers) as? NSDictionary {
guard let error = dict["message"] as? String else { return }
/*
0: Unknown transport
1: Unknown sid
2: Bad handshake request
3: Bad request
*/
didError(error)
}
} catch {
client?.engineDidError("Got unknown error from server \(msg)")
}
}
private func checkIfMessageIsBase64Binary(message: String) -> Bool {
if message.hasPrefix("b4") {
// binary in base64 string
let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex]
if let data = NSData(base64EncodedString: noPrefix, options: .IgnoreUnknownCharacters) {
client?.parseEngineBinaryData(data)
}
let dict = try msg.toNSDictionary()
guard let error = dict["message"] as? String else { return }
return true
} else {
return false
/*
0: Unknown transport
1: Unknown sid
2: Bad handshake request
3: Bad request
*/
didError(reason: error)
} catch {
client?.engineDidError(reason: "Got unknown error from server \(msg)")
}
}
private func handleBase64(message: String) {
// binary in base64 string
let noPrefix = message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex]
if let data = NSData(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) {
client?.parseEngineBinaryData(data as Data)
}
}
private func closeOutEngine(reason: String) {
sid = ""
closed = true
invalidated = true
connected = false
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
client?.engineDidClose(reason: 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)
disconnect("reconnect")
disconnect(reason: "reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: logType, args: url)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: urlPolling)
let reqPolling = NSMutableURLRequest(url: urlPolling)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
dispatch_async(emitQueue) {
self.doLongPoll(reqPolling)
}
doLongPoll(for: reqPolling as URLRequest)
}
private func createURLs() -> (NSURL, NSURL) {
private func createURLs() -> (URL, URL) {
if client == nil {
return (NSURL(), NSURL())
return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!)
}
let urlPolling = NSURLComponents(string: url.absoluteString)!
let urlWebSocket = NSURLComponents(string: url.absoluteString)!
var urlPolling = URLComponents(string: url.absoluteString)!
var urlWebSocket = URLComponents(string: url.absoluteString)!
var queryString = ""
urlWebSocket.path = socketPath
@@ -245,15 +238,15 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
return (urlPolling.URL!, urlWebSocket.URL!)
return (urlPolling.url!, urlWebSocket.url!)
}
private func createWebsocketAndConnect() {
ws = WebSocket(url: urlWebSocketWithSid)
ws = WebSocket(url: urlWebSocketWithSid as URL)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
@@ -265,46 +258,46 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
}
}
ws?.queue = handleQueue
ws?.callbackQueue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
ws?.selfSignedSSL = selfSigned
ws?.disableSSLCertValidation = selfSigned
ws?.security = security
ws?.connect()
}
public func didError(error: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: error)
client?.engineDidError(error)
disconnect(error)
public func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
client?.engineDidError(reason: reason)
disconnect(reason: reason)
}
public func disconnect(reason: String) {
guard connected else { return closeOutEngine(reason) }
guard connected else { return closeOutEngine(reason: reason) }
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return closeOutEngine(reason)
return closeOutEngine(reason: reason)
}
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
closeOutEngine(reason)
sendWebSocketMessage("", withType: .close, withData: [])
closeOutEngine(reason: reason)
} else {
disconnectPolling(reason)
disconnectPolling(reason: reason)
}
}
// 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
private func disconnectPolling(reason: String) {
dispatch_sync(emitQueue) {
self.postWait.append(String(SocketEnginePacketType.Close.rawValue))
emitQueue.sync {
self.postWait.append(String(SocketEnginePacketType.close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(req) {_, _, _ in }
self.closeOutEngine(reason)
self.doRequest(for: req) {_, _, _ in }
self.closeOutEngine(reason: reason)
}
}
@@ -314,7 +307,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .Upgrade, withData: [])
sendWebSocketMessage("", withType: .upgrade, withData: [])
websocket = true
polling = false
fastUpgrade = false
@@ -325,132 +318,139 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
dispatch_async(emitQueue) {
emitQueue.async {
for waiter in self.probeWait {
self.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self.probeWait.removeAll(keepCapacity: false)
self.probeWait.removeAll(keepingCapacity: false)
if self.postWait.count != 0 {
self.flushWaitingForPostToWebSocket()
}
}
}
// We had packets waiting for send when we upgraded
// Send them raw
public func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else { return }
for msg in postWait {
ws.writeString(msg)
ws.write(string: msg)
}
postWait.removeAll(keepCapacity: true)
postWait.removeAll(keepingCapacity: false)
}
private func handleClose(reason: String) {
client?.engineDidClose(reason)
private func handleClose(_ reason: String) {
client?.engineDidClose(reason: reason)
}
private func handleMessage(message: String) {
private func handleMessage(_ message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let sid = json?["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json?["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen("Connect")
}
} catch {
didError("Error parsing open packet")
guard let json = try? openData.toNSDictionary() else {
didError(reason: "Error parsing open packet")
return
}
guard let sid = json["sid"] as? String else {
didError(reason: "Open packet contained no sid")
return
}
let upgradeWs: Bool
self.sid = sid
connected = true
pongsMissed = 0
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen(reason: "Connect")
}
private func handlePong(pongMessage: String) {
private func handlePong(with message: String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
if message == "3probe" {
upgradeTransport()
}
}
public func parseEngineData(data: NSData) {
public func parseEngineData(_ data: Data) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
}
public func parseEngineMessage(message: String, fromPolling: Bool) {
public func parseEngineMessage(_ message: String, fromPolling: Bool) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let reader = SocketStringReader(message: message)
let fixedString: String
if message.hasPrefix("b4") {
return handleBase64(message: message)
}
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
if !checkIfMessageIsBase64Binary(message) {
checkAndHandleEngineError(message)
}
checkAndHandleEngineError(message)
return
}
if fromPolling && type != .Noop && doubleEncodeUTF8 {
if fromPolling && type != .noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
}
switch type {
case .Message:
handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Noop:
case .message:
handleMessage(String(fixedString.characters.dropFirst()))
case .noop:
handleNOOP()
case .Pong:
handlePong(fixedString)
case .Open:
handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Close:
case .pong:
handlePong(with: fixedString)
case .open:
handleOpen(openData: String(fixedString.characters.dropFirst()))
case .close:
handleClose(fixedString)
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
@@ -459,9 +459,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
polling = true
probing = false
invalidated = false
session = NSURLSession(configuration: .defaultSessionConfiguration(),
delegate: sessionDelegate,
delegateQueue: NSOperationQueue())
session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
sid = ""
waitingForPoll = false
waitingForPost = false
@@ -469,43 +467,40 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
}
private func sendPing() {
if !connected {
return
}
//Server is not responding
guard connected else { return }
// Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose("Ping timeout")
client?.engineDidClose(reason: "Ping timeout")
return
}
guard let pingInterval = pingInterval else { return }
if let pingInterval = pingInterval {
pongsMissed += 1
write("", withType: .Ping, withData: [])
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(pingInterval * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {[weak self] in
self?.sendPing()
}
}
pongsMissed += 1
write("", withType: .ping, withData: [])
let time = DispatchTime.now() + Double(Int64(pingInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {[weak self] in self?.sendPing() }
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: .Noop, withData: [])
sendPollMessage("", withType: .noop, withData: [])
// After this point, we should not send anymore polling messages
}
}
/// Write a message, independent of transport.
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) {
dispatch_async(emitQueue) {
public func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) {
emitQueue.async {
guard self.connected else { return }
if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
@@ -519,7 +514,7 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
}
}
}
// Delegate methods
public func websocketDidConnect(socket: WebSocket) {
if !forceWebsockets {
@@ -531,26 +526,35 @@ public final class SocketEngine : NSObject, SocketEnginePollable, SocketEngineWe
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
probing = false
if closed {
client?.engineDidClose("Disconnect")
client?.engineDidClose(reason: "Disconnect")
return
}
if websocket {
connected = false
websocket = false
if let reason = error?.localizedDescription {
didError(reason)
didError(reason: reason)
} else {
client?.engineDidClose("Socket Disconnected")
client?.engineDidClose(reason: "Socket Disconnected")
}
} else {
flushProbeWait()
}
}
}
extension SocketEngine {
public func URLSession(session: URLSession, didBecomeInvalidWithError error: NSError?) {
DefaultSocketLogger.Logger.error("Engine URLSession became invalid", type: "SocketEngine")
didError(reason: "Engine URLSession became invalid")
}
}
+2 -2
View File
@@ -29,6 +29,6 @@ import Foundation
func engineDidError(reason: String)
func engineDidClose(reason: String)
func engineDidOpen(reason: String)
func parseEngineMessage(msg: String)
func parseEngineBinaryData(data: NSData)
func parseEngineMessage(_ msg: String)
func parseEngineBinaryData(_ data: Data)
}
+1 -1
View File
@@ -26,5 +26,5 @@
import Foundation
@objc public enum SocketEnginePacketType : Int {
case Open, Close, Ping, Pong, Message, Upgrade, Noop
case open, close, ping, pong, message, upgrade, noop
}
+41 -43
View File
@@ -30,7 +30,7 @@ public protocol SocketEnginePollable : SocketEngineSpec {
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
var postWait: [String] { get set }
var session: NSURLSession? { get }
var session: URLSession? { get }
/// Because socket.io doesn't let you send two polling request at the same time
/// we have to keep track if there's an outstanding poll
var waitingForPoll: Bool { get set }
@@ -39,15 +39,17 @@ public protocol SocketEnginePollable : SocketEngineSpec {
var waitingForPost: Bool { get set }
func doPoll()
func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData])
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data])
func stopPolling()
}
// Default polling methods
extension SocketEnginePollable {
private func addHeaders(req: NSMutableURLRequest) {
private func addHeaders(for req: URLRequest) -> URLRequest {
var req = req
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
req.allHTTPHeaderFields = headers
}
@@ -56,9 +58,13 @@ extension SocketEnginePollable {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
return req
}
func createRequestForPostWithPostWait() -> NSURLRequest {
func createRequestForPostWithPostWait() -> URLRequest {
defer { postWait.removeAll(keepingCapacity: true) }
var postStr = ""
for packet in postWait {
@@ -69,22 +75,18 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
postWait.removeAll(keepCapacity: false)
var req = URLRequest(url: urlPollingWithSid)
let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
let req = NSMutableURLRequest(URL: urlPollingWithSid)
req = addHeaders(for: req)
addHeaders(req)
req.HTTPMethod = "POST"
req.httpMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
req.httpBody = postData
req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
return req
return req as URLRequest
}
public func doPoll() {
@@ -93,32 +95,32 @@ extension SocketEnginePollable {
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: urlPollingWithSid)
addHeaders(req)
doLongPoll(req)
var req = URLRequest(url: urlPollingWithSid)
req = addHeaders(for: req)
doLongPoll(for: req )
}
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
if !polling || closed || invalidated || fastUpgrade {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
session?.dataTask(with: req, completionHandler: callback).resume()
}
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self where this.polling else { return }
func doLongPoll(for req: URLRequest) {
doRequest(for: req) {[weak self] data, res, err in
guard let this = self, this.polling else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(err?.localizedDescription ?? "Error")
this.didError(reason: err?.localizedDescription ?? "Error")
}
return
@@ -126,8 +128,8 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
dispatch_async(this.parseQueue) {
if let str = String(data: data!, encoding: String.Encoding.utf8) {
this.parseQueue.async {
this.parsePollingMessage(str)
}
}
@@ -156,14 +158,14 @@ extension SocketEnginePollable {
DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
doRequest(req) {[weak self] data, res, err in
doRequest(for: req) {[weak self] data, res, err in
guard let this = self else { return }
if err != nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(err?.localizedDescription ?? "Error")
this.didError(reason: err?.localizedDescription ?? "Error")
}
return
@@ -171,7 +173,7 @@ extension SocketEnginePollable {
this.waitingForPost = false
dispatch_async(this.emitQueue) {
this.emitQueue.async {
if !this.fastUpgrade {
this.flushWaitingForPost()
this.doPoll()
@@ -180,22 +182,18 @@ extension SocketEnginePollable {
}
}
func parsePollingMessage(str: String) {
func parsePollingMessage(_ str: String) {
guard str.characters.count != 1 else { return }
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilStringOccurence(":")) {
let str = reader.read(n)
if let n = Int(reader.readUntilOccurence(of: ":")) {
let str = reader.read(count: n)
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
} else {
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
break
}
}
@@ -203,7 +201,7 @@ extension SocketEnginePollable {
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage: String
@@ -216,7 +214,7 @@ extension SocketEnginePollable {
postWait.append(String(type.rawValue) + fixedMessage)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
if case let .right(bin) = createBinaryDataForSend(using: data) {
postWait.append(bin)
}
}
+32 -32
View File
@@ -29,79 +29,79 @@ import Foundation
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: AnyObject]? { get set }
var connectParams: [String: Any]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [NSHTTPCookie]? { get }
var cookies: [HTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: dispatch_queue_t! { get }
var parseQueue: DispatchQueue { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: dispatch_queue_t! { get }
var handleQueue: dispatch_queue_t! { get }
var emitQueue: DispatchQueue { get }
var handleQueue: DispatchQueue { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: NSURL { get }
var urlWebSocket: NSURL { get }
var urlPolling: URL { get }
var urlWebSocket: URL { get }
var websocket: Bool { get }
var ws: WebSocket? { get }
init(client: SocketEngineClient, url: NSURL, options: NSDictionary?)
init(client: SocketEngineClient, url: URL, options: NSDictionary?)
func connect()
func didError(error: String)
func didError(reason: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
func parseEngineData(_ data: Data)
func parseEngineMessage(_ message: String, fromPolling: Bool)
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data])
}
extension SocketEngineSpec {
var urlPollingWithSid: NSURL {
let com = NSURLComponents(URL: urlPolling, resolvingAgainstBaseURL: false)!
var urlPollingWithSid: URL {
var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
return com.URL!
return com.url!
}
var urlWebSocketWithSid: NSURL {
let com = NSURLComponents(URL: urlWebSocket, resolvingAgainstBaseURL: false)!
var urlWebSocketWithSid: URL {
var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
return com.URL!
return com.url!
}
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
var byteArray = [UInt8](repeating: 0x4, count: 1)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
mutData.append(data)
return .Left(mutData)
return .left(mutData as Data)
} else {
let str = "b4" + data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let str = "b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
return .Right(str)
return .right(str)
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
func doubleEncodeUTF8(_ string: String) -> String {
if let latin1 = string.data(using: String.Encoding.utf8),
let utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
func fixDoubleUTF8(_ string: String) -> String {
if let utf8 = string.data(using: String.Encoding.isoLatin1),
let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) {
return latin1 as String
} else {
return string
@@ -109,7 +109,7 @@ extension SocketEngineSpec {
}
/// Send an engine message (4)
func send(msg: String, withData datas: [NSData]) {
write(msg, withType: .Message, withData: datas)
func send(_ msg: String, withData datas: [Data]) {
write(msg, withType: .message, withData: datas)
}
}
+12 -12
View File
@@ -27,36 +27,36 @@ import Foundation
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data])
}
// WebSocket methods
extension SocketEngineWebsocket {
func probeWebSocket() {
if ws?.isConnected ?? false {
sendWebSocketMessage("probe", withType: .Ping, withData: [])
sendWebSocketMessage("probe", withType: .ping, withData: [])
}
}
/// Send message on WebSockets
/// Only call on emitQueue
public func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas {
if case let .Left(bin) = createBinaryDataForSend(data) {
ws?.writeData(bin)
}
public func sendWebSocketMessage(_ str: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.write(string: "\(type.rawValue)\(str)")
for data in datas {
if case let .left(bin) = createBinaryDataForSend(using: data) {
ws?.write(data: bin)
}
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
public func websocketDidReceiveData(socket: WebSocket, data: Data) {
parseEngineData(data)
}
}
+2 -2
View File
@@ -26,10 +26,10 @@ import Foundation
struct SocketEventHandler {
let event: String
let id: NSUUID
let id: UUID
let callback: NormalCallback
func executeCallback(items: [AnyObject], withAck ack: Int, withSocket socket: SocketIOClient) {
func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
}
}
+127
View File
@@ -0,0 +1,127 @@
//
// SocketExtensions.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 7/1/2016.
//
// 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
enum JSONError : Error {
case notArray
case notNSDictionary
}
extension Array {
func toJSON() throws -> Data {
return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
}
}
extension CharacterSet {
static var allowedURLCharacterSet: CharacterSet {
return CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]\" {}").inverted
}
}
extension NSDictionary {
private static func keyValueToSocketIOClientOption(key: String, value: Any) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: Any]):
return .connectParams(params)
case let ("cookies", cookies as [HTTPCookie]):
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 ("handleQueue", queue as DispatchQueue):
return .handleQueue(queue)
case let ("log", log as Bool):
return .log(log)
case let ("logger", logger as SocketLogger):
return .logger(logger)
case let ("nsp", nsp as String):
return .nsp(nsp)
case let ("path", path as String):
return .path(path)
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 ("security", security as SSLSecurity):
return .security(security)
case let ("selfSigned", selfSigned as Bool):
return .selfSigned(selfSigned)
case let ("sessionDelegate", delegate as URLSessionDelegate):
return .sessionDelegate(delegate)
case let ("voipEnabled", enable as Bool):
return .voipEnabled(enable)
default:
return nil
}
}
func toSocketConfiguration() -> SocketIOClientConfiguration {
var options = [] as SocketIOClientConfiguration
for (rawKey, value) in self {
if let key = rawKey as? String, let opt = NSDictionary.keyValueToSocketIOClientOption(key: key, value: value) {
options.insert(opt)
}
}
return options
}
}
extension String {
func toArray() throws -> [Any] {
guard let stringData = data(using: .utf8, allowLossyConversion: false) else { return [] }
guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
throw JSONError.notArray
}
return array
}
func toNSDictionary() throws -> NSDictionary {
guard let binData = data(using: .utf8, allowLossyConversion: false) else { return [:] }
guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? NSDictionary else {
throw JSONError.notNSDictionary
}
return json
}
func urlEncode() -> String? {
return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
}
}
+138 -144
View File
@@ -25,13 +25,13 @@
import Foundation
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
public let socketURL: NSURL
public let socketURL: URL
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected {
public private(set) var status = SocketIOClientStatus.notConnected {
didSet {
switch status {
case .Connected:
case .connected:
reconnecting = false
currentReconnectAttempt = 0
default:
@@ -42,100 +42,105 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
public var config: SocketIOClientConfiguration
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return nsp + "#" + (engine?.sid ?? "")
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private let parseQueue = DispatchQueue(label: "com.socketio.parseQueue")
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var ackHandlers = SocketAckManager()
private var reconnecting = false
private let ackSemaphore = DispatchSemaphore(value: 1)
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var handleQueue = DispatchQueue.main
private(set) var reconnectAttempts = -1
let ackQueue = DispatchQueue(label: "com.socketio.ackQueue")
let emitQueue = DispatchQueue(label: "com.socketio.emitQueue")
var ackHandlers = SocketAckManager()
var waitingPackets = [SocketPacket]()
public var sid: String? {
return engine?.sid
}
/// Type safe way to create a new SocketIOClient. opts can be omitted
public init(socketURL: NSURL, options: Set<SocketIOClientOption> = []) {
self.options = options
public init(socketURL: URL, config: SocketIOClientConfiguration = []) {
self.config = config
self.socketURL = socketURL
if socketURL.absoluteString.hasPrefix("https://") {
self.options.insertIgnore(.Secure(true))
self.config.insert(.secure(true))
}
for option in options {
for option in config {
switch option {
case let .Reconnects(reconnects):
case let .reconnects(reconnects):
self.reconnects = reconnects
case let .ReconnectAttempts(attempts):
case let .reconnectAttempts(attempts):
reconnectAttempts = attempts
case let .ReconnectWait(wait):
case let .reconnectWait(wait):
reconnectWait = abs(wait)
case let .Nsp(nsp):
case let .nsp(nsp):
self.nsp = nsp
case let .Log(log):
case let .log(log):
DefaultSocketLogger.Logger.log = log
case let .Logger(logger):
case let .logger(logger):
DefaultSocketLogger.Logger = logger
case let .HandleQueue(queue):
case let .handleQueue(queue):
handleQueue = queue
case let .ForceNew(force):
case let .forceNew(force):
forceNew = force
default:
continue
}
}
self.options.insertIgnore(.Path("/socket.io/"))
self.config.insert(.path("/socket.io/"), replacing: false)
super.init()
}
/// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
/// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
public convenience init(socketURL: NSURL, options: NSDictionary?) {
self.init(socketURL: socketURL, options: options?.toSocketOptionsSet() ?? [])
public convenience init(socketURL: NSURL, config: NSDictionary?) {
self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.disconnect("Client Deinit")
engine?.disconnect(reason: "Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
DefaultSocketLogger.Logger.log("Adding engine", type: logType, args: "")
engine = SocketEngine(client: self, url: socketURL, options: options)
engine = SocketEngine(client: self, url: socketURL, config: config)
return engine!
}
/// Connect to the server.
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
connect(timeoutAfter: 0, withHandler: nil)
}
/// Connect to the server. If we aren't connected after timeoutAfter, call handler
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?) {
/// Connect to the server. If we aren't connected after timeoutAfter, call withHandler
/// 0 Never times out
public func connect(timeoutAfter: Int, withHandler handler: (() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
guard status != .connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
return
}
status = .Connecting
status = .connecting
if engine == nil || forceNew {
addEngine().connect()
@@ -145,40 +150,32 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
let time = DispatchTime.now() + Double(UInt64(timeoutAfter) * NSEC_PER_SEC) / Double(NSEC_PER_SEC)
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected && this.status != .Disconnected {
this.status = .Disconnected
this.engine?.disconnect("Connect timeout")
handler?()
}
handleQueue.asyncAfter(deadline: time) {[weak self] in
guard let this = self, this.status != .connected && this.status != .disconnected else { return }
this.status = .disconnected
this.engine?.disconnect(reason: "Connect timeout")
handler?()
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
private func nextAck() -> Int {
ackSemaphore.wait()
defer { ackSemaphore.signal() }
currentAck += 1
return currentAck
}
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
this._emit(items, ack: ack)
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, this.handleQueue) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
private func createOnAck(_ items: [Any]) -> OnAckCallback {
return OnAckCallback(ackNumber: nextAck(), items: items, socket: self)
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
status = .connected
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
@@ -186,34 +183,33 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
func didDisconnect(reason: String) {
guard status != .Disconnected else { return }
guard status != .disconnected else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Disconnected
reconnecting = false
status = .disconnected
// Make sure the engine is actually dead.
engine?.disconnect(reason)
engine?.disconnect(reason: reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// Disconnects the socket.
public func disconnect() {
assert(status != .NotConnected, "Tried closing a NotConnected client")
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
didDisconnect("Disconnect")
didDisconnect(reason: "Disconnect")
}
/// Send a message to the server
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
public func emit(_ event: String, _ items: SocketData...) {
emit(event, with: items)
}
/// Same as emit, but meant for Objective-C
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
public func emit(_ event: String, with items: [Any]) {
guard status == .connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
@@ -223,18 +219,18 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
/// an ack.
public func emitWithAck(event: String, _ items: AnyObject...) -> OnAckCallback {
return emitWithAck(event, withItems: items)
public func emitWithAck(_ event: String, _ items: SocketData...) -> OnAckCallback {
return emitWithAck(event, with: items)
}
/// Same as emitWithAck, but for Objective-C
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
public func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
dispatch_async(emitQueue) {
guard self.status == .Connected else {
func _emit(_ data: [Any], ack: Int? = nil) {
emitQueue.async {
guard self.status == .connected else {
self.handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
@@ -249,31 +245,33 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
func emitAck(_ ack: Int, with items: [Any]) {
emitQueue.async {
guard self.status == .connected else { return }
let packet = SocketPacket.packetFromEmit(items, id: ack, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
public func engineDidClose(reason: String) {
waitingPackets.removeAll()
parseQueue.async {
self.waitingPackets.removeAll()
}
if status != .Disconnected {
status = .NotConnected
if status != .disconnected {
status = .notConnected
}
if status == .Disconnected || !reconnects {
didDisconnect(reason)
if status == .disconnected || !reconnects {
didDisconnect(reason: reason)
} else if !reconnecting {
reconnecting = true
tryReconnectWithReason(reason)
tryReconnect(reason: reason)
}
}
@@ -289,25 +287,27 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else { return }
func handleAck(_ ack: Int, data: [Any]) {
guard status == .connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data)
ackHandlers.executeAck(ack, items: data)
handleQueue.async() {
self.ackHandlers.executeAck(ack, with: data, onQueue: self.handleQueue)
}
}
/// Causes an event to be handled. Only use if you know what you're doing.
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else { return }
public func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .connected || isInternalMessage else { return }
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data)
dispatch_async(handleQueue) {
handleQueue.async {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(data, withAck: ack, withSocket: self)
handler.executeCallback(with: data, withAck: ack, withSocket: self)
}
}
}
@@ -321,7 +321,7 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Joins namespace
public func joinNamespace(namespace: String) {
public func joinNamespace(_ namespace: String) {
nsp = namespace
if nsp != "/" {
@@ -331,14 +331,14 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Removes handler(s) based on name
public func off(event: String) {
public func off(_ event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter({ $0.event != event })
}
/// Removes a handler with the specified UUID gotten from an `on` or `once`
public func off(id id: NSUUID) {
public func off(id: UUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter({ $0.id != id })
@@ -346,10 +346,11 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Adds a handler for an event.
/// Returns: A unique id for the handler
public func on(event: String, callback: NormalCallback) -> NSUUID {
@discardableResult
public func on(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
let handler = SocketEventHandler(event: event, id: UUID(), callback: callback)
handlers.append(handler)
return handler.id
@@ -357,10 +358,11 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
/// Adds a single-use handler for an event.
/// Returns: A unique id for the handler
public func once(event: String, callback: NormalCallback) -> NSUUID {
@discardableResult
public func once(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
let id = UUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else { return }
@@ -374,83 +376,75 @@ public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable
}
/// Adds a handler that will be called on every event.
public func onAny(handler: (SocketAnyEvent) -> Void) {
public func onAny(_ handler: @escaping (SocketAnyEvent) -> Void) {
anyHandler = handler
}
public func parseEngineMessage(msg: String) {
public func parseEngineMessage(_ msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
dispatch_async(parseQueue) {
self.parseSocketMessage(msg)
}
parseQueue.async { self.parseSocketMessage(msg) }
}
public func parseEngineBinaryData(data: NSData) {
dispatch_async(parseQueue) {
self.parseBinaryData(data)
}
public func parseEngineBinaryData(_ data: Data) {
parseQueue.async { self.parseBinaryData(data) }
}
/// Tries to reconnect to the server.
public func reconnect() {
guard !reconnecting else { return }
engine?.disconnect("manual reconnect")
engine?.disconnect(reason: "manual reconnect")
}
/// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles.
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
handlers.removeAll(keepingCapacity: false)
}
private func tryReconnectWithReason(reason: String) {
if reconnecting {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
handleEvent("reconnect", data: [reason], isInternalMessage: true)
_tryReconnect()
}
private func tryReconnect(reason: String) {
guard reconnecting else { return }
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
handleEvent("reconnect", data: [reason], isInternalMessage: true)
_tryReconnect()
}
private func _tryReconnect() {
if !reconnecting {
return
}
guard reconnecting else { return }
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
return didDisconnect("Reconnect Failed")
return didDisconnect(reason: "Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
handleEvent("reconnectAttempt", data: [(reconnectAttempts - currentReconnectAttempt)], isInternalMessage: true)
currentReconnectAttempt += 1
connect()
let dispatchAfter = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(reconnectWait) * NSEC_PER_SEC))
let deadline = DispatchTime.now() + Double(Int64(UInt64(reconnectWait) * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
dispatch_after(dispatchAfter, dispatch_get_main_queue(), _tryReconnect)
DispatchQueue.main.asyncAfter(deadline: deadline, execute: _tryReconnect)
}
}
// Test extensions
extension SocketIOClient {
// Test properties
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
status = .connected
}
func setTestEngine(engine: SocketEngineSpec?) {
func setTestEngine(_ engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
func emitTest(event: String, _ data: Any...) {
_emit([event] + data)
}
}
+108
View File
@@ -0,0 +1,108 @@
//
// SocketIOClientConfiguration.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 8/13/16.
//
// 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.
public struct SocketIOClientConfiguration : ExpressibleByArrayLiteral, Collection, MutableCollection {
public typealias Element = SocketIOClientOption
public typealias Index = Array<SocketIOClientOption>.Index
public typealias Generator = Array<SocketIOClientOption>.Iterator
public typealias SubSequence = Array<SocketIOClientOption>.SubSequence
private var backingArray = [SocketIOClientOption]()
public var startIndex: Index {
return backingArray.startIndex
}
public var endIndex: Index {
return backingArray.endIndex
}
public var isEmpty: Bool {
return backingArray.isEmpty
}
public var count: Index.Stride {
return backingArray.count
}
public var first: Generator.Element? {
return backingArray.first
}
public subscript(position: Index) -> Generator.Element {
get {
return backingArray[position]
}
set {
backingArray[position] = newValue
}
}
public subscript(bounds: Range<Index>) -> SubSequence {
get {
return backingArray[bounds]
}
set {
backingArray[bounds] = newValue
}
}
public init(arrayLiteral elements: Element...) {
backingArray = elements
}
public func generate() -> Generator {
return backingArray.makeIterator()
}
public func index(after i: Index) -> Index {
return backingArray.index(after: i)
}
public mutating func insert(_ element: Element, replacing replace: Bool = true) {
for i in 0..<backingArray.count where backingArray[i] == element {
guard replace else { return }
backingArray[i] = element
return
}
backingArray.append(element)
}
public func prefix(upTo end: Index) -> SubSequence {
return backingArray.prefix(upTo: end)
}
public func prefix(through position: Index) -> SubSequence {
return backingArray.prefix(through: position)
}
public func suffix(from start: Index) -> SubSequence {
return backingArray.suffix(from: start)
}
}
+65 -138
View File
@@ -24,128 +24,124 @@
import Foundation
protocol ClientOption : CustomStringConvertible, Hashable {
func getSocketIOOptionValue() -> AnyObject
protocol ClientOption : CustomStringConvertible, Equatable {
func getSocketIOOptionValue() -> Any
}
public enum SocketIOClientOption : ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case DoubleEncodeUTF8(Bool)
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
case ForceWebsockets(Bool)
case HandleQueue(dispatch_queue_t)
case Log(Bool)
case Logger(SocketLogger)
case Nsp(String)
case Path(String)
case Reconnects(Bool)
case ReconnectAttempts(Int)
case ReconnectWait(Int)
case Secure(Bool)
case Security(SSLSecurity)
case SelfSigned(Bool)
case SessionDelegate(NSURLSessionDelegate)
case VoipEnabled(Bool)
case connectParams([String: Any])
case cookies([HTTPCookie])
case doubleEncodeUTF8(Bool)
case extraHeaders([String: String])
case forceNew(Bool)
case forcePolling(Bool)
case forceWebsockets(Bool)
case handleQueue(DispatchQueue)
case log(Bool)
case logger(SocketLogger)
case nsp(String)
case path(String)
case reconnects(Bool)
case reconnectAttempts(Int)
case reconnectWait(Int)
case secure(Bool)
case security(SSLSecurity)
case selfSigned(Bool)
case sessionDelegate(URLSessionDelegate)
case voipEnabled(Bool)
public var description: String {
let description: String
switch self {
case .ConnectParams:
case .connectParams:
description = "connectParams"
case .Cookies:
case .cookies:
description = "cookies"
case .DoubleEncodeUTF8:
case .doubleEncodeUTF8:
description = "doubleEncodeUTF8"
case .ExtraHeaders:
case .extraHeaders:
description = "extraHeaders"
case .ForceNew:
case .forceNew:
description = "forceNew"
case .ForcePolling:
case .forcePolling:
description = "forcePolling"
case .ForceWebsockets:
case .forceWebsockets:
description = "forceWebsockets"
case .HandleQueue:
case .handleQueue:
description = "handleQueue"
case .Log:
case .log:
description = "log"
case .Logger:
case .logger:
description = "logger"
case .Nsp:
case .nsp:
description = "nsp"
case .Path:
case .path:
description = "path"
case .Reconnects:
case .reconnects:
description = "reconnects"
case .ReconnectAttempts:
case .reconnectAttempts:
description = "reconnectAttempts"
case .ReconnectWait:
case .reconnectWait:
description = "reconnectWait"
case .Secure:
case .secure:
description = "secure"
case .Security:
description = "security"
case .SelfSigned:
case .selfSigned:
description = "selfSigned"
case .SessionDelegate:
case .security:
description = "security"
case .sessionDelegate:
description = "sessionDelegate"
case .VoipEnabled:
case .voipEnabled:
description = "voipEnabled"
}
return description
}
public var hashValue: Int {
return description.hashValue
}
func getSocketIOOptionValue() -> AnyObject {
let value: AnyObject
func getSocketIOOptionValue() -> Any {
let value: Any
switch self {
case let .ConnectParams(params):
case let .connectParams(params):
value = params
case let .Cookies(cookies):
case let .cookies(cookies):
value = cookies
case let .DoubleEncodeUTF8(encode):
case let .doubleEncodeUTF8(encode):
value = encode
case let .ExtraHeaders(headers):
case let .extraHeaders(headers):
value = headers
case let .ForceNew(force):
case let .forceNew(force):
value = force
case let .ForcePolling(force):
case let .forcePolling(force):
value = force
case let .ForceWebsockets(force):
case let .forceWebsockets(force):
value = force
case let .HandleQueue(queue):
case let .handleQueue(queue):
value = queue
case let .Log(log):
case let .log(log):
value = log
case let .Logger(logger):
case let .logger(logger):
value = logger
case let .Nsp(nsp):
case let .nsp(nsp):
value = nsp
case let .Path(path):
case let .path(path):
value = path
case let .Reconnects(reconnects):
case let .reconnects(reconnects):
value = reconnects
case let .ReconnectAttempts(attempts):
case let .reconnectAttempts(attempts):
value = attempts
case let .ReconnectWait(wait):
case let .reconnectWait(wait):
value = wait
case let .Secure(secure):
case let .secure(secure):
value = secure
case let .Security(security):
case let .security(security):
value = security
case let .SelfSigned(signed):
case let .selfSigned(signed):
value = signed
case let .SessionDelegate(delegate):
case let .sessionDelegate(delegate):
value = delegate
case let .VoipEnabled(enabled):
case let .voipEnabled(enabled):
value = enabled
}
@@ -156,72 +152,3 @@ public enum SocketIOClientOption : ClientOption {
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
return lhs.description == rhs.description
}
extension Set where Element : ClientOption {
mutating func insertIgnore(element: Element) {
if !contains(element) {
insert(element)
}
}
}
extension NSDictionary {
private static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
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 ("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 ("nsp", nsp as String):
return .Nsp(nsp)
case let ("path", path as String):
return .Path(path)
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 ("security", security as SSLSecurity):
return .Security(security)
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
}
}
func toSocketOptionsSet() -> Set<SocketIOClientOption> {
var options = Set<SocketIOClientOption>()
for (rawKey, value) in self {
if let key = rawKey as? String, opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) {
options.insertIgnore(opt)
}
}
return options
}
}
+3 -3
View File
@@ -29,9 +29,9 @@ protocol SocketIOClientSpec : class {
func didConnect()
func didDisconnect(reason: String)
func didError(reason: String)
func handleAck(ack: Int, data: [AnyObject])
func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(namespace: String)
func handleAck(_ ack: Int, data: [Any])
func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(_ namespace: String)
}
extension SocketIOClientSpec {
+1 -1
View File
@@ -28,5 +28,5 @@ import Foundation
///
/// **Disconnected**: connected before
@objc public enum SocketIOClientStatus : Int {
case NotConnected, Disconnected, Connecting, Connected
case notConnected, disconnected, connecting, connected
}
+8 -8
View File
@@ -29,28 +29,28 @@ public protocol SocketLogger : class {
var log: Bool { get set }
/// Normal log messages
func log(message: String, type: String, args: AnyObject...)
func log(_ message: String, type: String, args: Any...)
/// Error Messages
func error(message: String, type: String, args: AnyObject...)
func error(_ message: String, type: String, args: Any...)
}
public extension SocketLogger {
func log(message: String, type: String, args: AnyObject...) {
func log(_ message: String, type: String, args: Any...) {
abstractLog("LOG", message: message, type: type, args: args)
}
func error(message: String, type: String, args: AnyObject...) {
func error(_ message: String, type: String, args: Any...) {
abstractLog("ERROR", message: message, type: type, args: args)
}
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
private func abstractLog(_ logType: String, message: String, type: String, args: [Any]) {
guard log else { return }
let newArgs = args.map({arg -> CVarArgType in String(arg)})
let replaced = String(format: message, arguments: newArgs)
let newArgs = args.map({arg -> CVarArg in String(describing: arg)})
let messageFormat = String(format: message, arguments: newArgs)
NSLog("%@ %@: %@", logType, type, replaced)
NSLog("\(logType) \(type): %@", messageFormat)
}
}
+53 -71
View File
@@ -26,6 +26,10 @@
import Foundation
struct SocketPacket {
enum PacketType: Int {
case connect, disconnect, event, ack, error, binaryEvent, binaryAck
}
private let placeholders: Int
private static let logType = "SocketPacket"
@@ -34,35 +38,31 @@ struct SocketPacket {
let id: Int
let type: PacketType
enum PacketType: Int {
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
}
var args: [AnyObject] {
if type == .Event || type == .BinaryEvent && data.count != 0 {
var binary: [Data]
var data: [Any]
var args: [Any] {
if type == .event || type == .binaryEvent && data.count != 0 {
return Array(data.dropFirst())
} else {
return data
}
}
var binary: [NSData]
var data: [AnyObject]
var description: String {
return "SocketPacket {type: \(String(type.rawValue)); data: " +
"\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
"\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
}
var event: String {
return String(data[0])
return String(describing: data[0])
}
var packetString: String {
return createPacketString()
}
init(type: PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1,
nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) {
init(type: PacketType, data: [Any] = [Any](), id: Int = -1, nsp: String, placeholders: Int = 0,
binary: [Data] = [Data]()) {
self.data = data
self.id = id
self.nsp = nsp
@@ -71,7 +71,7 @@ struct SocketPacket {
self.binary = binary
}
mutating func addData(data: NSData) -> Bool {
mutating func addData(_ data: Data) -> Bool {
if placeholders == binary.count {
return true
}
@@ -86,54 +86,29 @@ struct SocketPacket {
}
}
private func completeMessage(message: String) -> String {
let restOfMessage: String
private func completeMessage(_ message: String) -> String {
if data.count == 0 {
return message + "[]"
}
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(data,
options: NSJSONWritingOptions(rawValue: 0))
guard let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding) else {
return message + "[]"
}
restOfMessage = jsonString
} catch {
guard let jsonSend = try? data.toJSON(), let jsonString = String(data: jsonSend, encoding: .utf8) else {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
type: SocketPacket.logType)
restOfMessage = "[]"
return message + "[]"
}
return message + restOfMessage
return message + jsonString
}
private func createPacketString() -> String {
let typeString = String(type.rawValue)
let binaryCountString: String
let nspString: String
let idString: String
if type == .BinaryEvent || type == .BinaryAck {
binaryCountString = typeString + String(binary.count) + "-"
} else {
binaryCountString = typeString
}
if nsp != "/" {
nspString = binaryCountString + nsp + ","
} else {
nspString = binaryCountString
}
if id != -1 {
idString = nspString + String(id)
} else {
idString = nspString
}
// Binary count?
let binaryCountString = typeString + (type == .binaryEvent || type == .binaryAck ? "\(String(binary.count))-" : "")
// Namespace?
let nspString = binaryCountString + (nsp != "/" ? "\(nsp)," : "")
// Ack number?
let idString = nspString + (id != -1 ? String(id) : "")
return completeMessage(idString)
}
@@ -149,18 +124,21 @@ struct SocketPacket {
// If object is a collection it will recurse
// Returns the object if it is not a placeholder or the corresponding
// binary data
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
private func _fillInPlaceholders(_ object: Any) -> Any {
switch object {
case let dict as NSDictionary:
case let dict as JSON:
if dict["_placeholder"] as? Bool ?? false {
return binary[dict["num"] as! Int]
} else {
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
return dict.reduce(JSON(), {cur, keyValue in
var cur = cur
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
return cur
})
}
case let arr as [AnyObject]:
case let arr as [Any]:
return arr.map(_fillInPlaceholders)
default:
return object
@@ -169,22 +147,22 @@ struct SocketPacket {
}
extension SocketPacket {
private static func findType(binCount: Int, ack: Bool) -> PacketType {
private static func findType(_ binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return .Event
return .event
case 0 where ack:
return .Ack
return .ack
case _ where !ack:
return .BinaryEvent
return .binaryEvent
case _ where ack:
return .BinaryAck
return .binaryAck
default:
return .Error
return .error
}
}
static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket {
static func packetFromEmit(_ items: [Any], id: Int, nsp: String, ack: Bool) -> SocketPacket {
let (parsedData, binary) = deconstructData(items)
let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData,
id: id, nsp: nsp, binary: binary)
@@ -195,19 +173,23 @@ extension SocketPacket {
private extension SocketPacket {
// Recursive function that looks for NSData in collections
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
let placeholder = ["_placeholder": true, "num": binary.count]
static func shred(_ data: Any, binary: inout [Data]) -> Any {
let placeholder = ["_placeholder": true, "num": binary.count] as JSON
switch data {
case let bin as NSData:
case let bin as Data:
binary.append(bin)
return placeholder
case let arr as [AnyObject]:
case let arr as [Any]:
return arr.map({shred($0, binary: &binary)})
case let dict as NSDictionary:
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary)
return cur
case let dict as JSON:
return dict.reduce(JSON(), {cur, keyValue in
var mutCur = cur
mutCur[keyValue.0] = shred(keyValue.1, binary: &binary)
return mutCur
})
default:
return data
@@ -216,8 +198,8 @@ private extension SocketPacket {
// Removes binary data from emit data
// Returns a type containing the de-binaryed data and the binary
static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
var binary = [NSData]()
static func deconstructData(_ data: [Any]) -> ([Any], [Data]) {
var binary = [Data]()
return (data.map({shred($0, binary: &binary)}), binary)
}
+54 -62
View File
@@ -23,38 +23,38 @@
import Foundation
protocol SocketParsable : SocketIOClientSpec {
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
func parseBinaryData(_ data: Data)
func parseSocketMessage(_ message: String)
}
extension SocketParsable {
private func isCorrectNamespace(nsp: String) -> Bool {
private func isCorrectNamespace(_ nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(p: SocketPacket) {
if p.nsp == "/" && nsp != "/" {
private func handleConnect(_ packetNamespace: String) {
if packetNamespace == "/" && nsp != "/" {
joinNamespace(nsp)
} else {
didConnect()
}
}
private func handlePacket(pack: SocketPacket) {
private func handlePacket(_ pack: SocketPacket) {
switch pack.type {
case .Event where isCorrectNamespace(pack.nsp):
case .event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
case .Ack where isCorrectNamespace(pack.nsp):
case .ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .BinaryEvent where isCorrectNamespace(pack.nsp):
case .binaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
case .binaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
didDisconnect("Got Disconnect")
case .Error:
case .connect:
handleConnect(pack.nsp)
case .disconnect:
didDisconnect(reason: "Got Disconnect")
case .error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
@@ -62,100 +62,93 @@ extension SocketParsable {
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(message: String) -> Either<String, SocketPacket> {
var parser = SocketStringReader(message: message)
func parseString(_ message: String) -> Either<String, SocketPacket> {
var reader = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
return .Left("Invalid packet type")
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
return .left("Invalid packet type")
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, nsp: "/"))
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
if type == .binaryEvent || type == .binaryAck {
if let holders = Int(reader.readUntilOccurence(of: "-")) {
placeholders = holders
} else {
return .Left("Invalid packet")
return .left("Invalid packet")
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
if reader.currentCharacter == "/" {
namespace = reader.readUntilOccurence(of: ",")
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
}
var idString = ""
if type == .Error {
parser.advanceIndexBy(-1)
if type == .error {
reader.advance(by: -1)
} else {
while parser.hasNext {
if let int = Int(parser.read(1)) {
while reader.hasNext {
if let int = Int(reader.read(count: 1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
reader.advance(by: -2)
break
}
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
switch parseData(d) {
case let .Left(err):
// Errors aren't always enclosed in an array
if case let .Right(data) = parseData("\([d as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
} else {
return .Left(err)
}
case let .Right(data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
var dataArray = message[message.characters.index(reader.currentIndex, offsetBy: 1)..<message.endIndex]
if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") {
dataArray = "[" + dataArray + "]"
}
switch parseData(dataArray) {
case let .left(err):
return .left(err)
case let .right(data):
return .right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
private func parseData(_ data: String) -> Either<String, [Any]> {
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
return .right(try data.toArray())
} catch {
return .Left("Error parsing data for packet")
return .left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(message: String) {
func parseSocketMessage(_ message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .Left(err):
case let .left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .Right(pack):
case let .right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(data: NSData) {
func parseBinaryData(_ data: Data) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
@@ -166,9 +159,8 @@ extension SocketParsable {
let packet = waitingPackets.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, withAck: packet.id)
if packet.type != .binaryAck {
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
+15 -10
View File
@@ -38,31 +38,36 @@ struct SocketStringReader {
currentIndex = message.startIndex
}
mutating func advanceIndexBy(n: Int) {
currentIndex = currentIndex.advancedBy(n)
@discardableResult
mutating func advance(by: Int) -> String.Index {
currentIndex = message.characters.index(currentIndex, offsetBy: by)
return currentIndex
}
mutating func read(readLength: Int) -> String {
let readString = message[currentIndex..<currentIndex.advancedBy(readLength)]
advanceIndexBy(readLength)
mutating func read(count: Int) -> String {
let readString = message[currentIndex..<message.characters.index(currentIndex, offsetBy: count)]
advance(by: count)
return readString
}
mutating func readUntilStringOccurence(string: String) -> String {
mutating func readUntilOccurence(of string: String) -> String {
let substring = message[currentIndex..<message.endIndex]
guard let foundRange = substring.rangeOfString(string) else {
guard let foundRange = substring.range(of: string) else {
currentIndex = message.endIndex
return substring
}
advanceIndexBy(message.startIndex.distanceTo(foundRange.startIndex) + 1)
advance(by: message.characters.distance(from: message.characters.startIndex, to: foundRange.lowerBound) + 1)
return substring.substringToIndex(foundRange.startIndex)
return substring.substring(to: foundRange.lowerBound)
}
mutating func readUntilEnd() -> String {
return read(currentIndex.distanceTo(message.endIndex))
return read(count: message.characters.distance(from: currentIndex, to: message.endIndex))
}
}
+21 -6
View File
@@ -24,14 +24,29 @@
import Foundation
public typealias AckCallback = ([AnyObject]) -> Void
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
public protocol SocketData {}
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
extension Array : SocketData {}
extension Bool : SocketData {}
extension Dictionary : SocketData {}
extension Double : SocketData {}
extension Int : SocketData {}
extension NSArray : SocketData {}
extension Data : SocketData {}
extension NSData : SocketData {}
extension NSDictionary : SocketData {}
extension NSString : SocketData {}
extension NSNull : SocketData {}
extension String : SocketData {}
public typealias AckCallback = ([Any]) -> Void
public typealias NormalCallback = ([Any], SocketAckEmitter) -> Void
typealias JSON = [String: Any]
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data])
typealias ProbeWaitQueue = [Probe]
enum Either<E, V> {
case Left(E)
case Right(V)
case left(E)
case right(V)
}
-31
View File
@@ -1,31 +0,0 @@
//
// String.swift
// Socket.IO-Client-Swift
//
// Created by Yannick Loriot on 5/4/16.
//
// 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
extension String {
func urlEncode() -> String? {
return stringByAddingPercentEncodingWithAllowedCharacters(.allowedURLCharacterSet)
}
}
+955
View File
@@ -0,0 +1,955 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2016 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import Security
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: Data)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket, data: Data?)
}
open class WebSocket : NSObject, StreamDelegate {
enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public static let ErrorDomain = "WebSocket"
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case outputStreamWriteError = 1
}
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
var optionalProtocols: [String]?
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
class WSResponse {
var isFin = false
var code: OpCode = .continueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
// MARK: - Block based API.
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var headers = [String: String]()
public var voipEnabled = false
public var disableSSLCertValidation = false
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var timeout = 5
public var isConnected: Bool {
return connected
}
public var currentURL: URL { return url }
// MARK: - Private
private var url: URL
private var inputStream: InputStream?
private var outputStream: OutputStream?
private var connected = false
private var isConnecting = false
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private let notificationCenter = NotificationCenter.default
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// The shared processing queue used for all WebSocket.
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
/// Used for setting protocols.
public init(url: URL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
var origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
self.origin = origin
}
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString,
url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key, value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest as Data, Int(port!))
}
}
/**
Add a header to the CFHTTPMessage by using the NSString bridges to CFString
*/
private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if supportedSSLSchemes.contains(url.scheme!) {
certValidated = false
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
if disableSSLCertValidation {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
var out = timeout * 1_000_000 // wait 5 seconds before giving up
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation else { return }
while !outStream.hasSpaceAvailable && !sOperation.isCancelled {
usleep(100) // wait until the socket is ready
guard !sOperation.isCancelled else { return }
out -= 100
if out < 0 {
WebSocket.sharedWorkQueue.async {
self?.cleanupStream()
}
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return // disconnectStream will be called.
}
}
guard !sOperation.isCancelled, let s = self else { return }
// Do the pinning now if needed
if let sec = s.security, !s.certValidated {
let trust = outStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust
let domain = outStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
s.certValidated = sec.isValid(trust, domain: domain)
if !s.certValidated {
WebSocket.sharedWorkQueue.async {
let error = s.errorWithDetail("Invalid SSL certificate", code: 1)
s.disconnectStream(error)
}
return
}
}
outStream.write(bytes, maxLength: data.count)
}
writeQueue.addOperation(operation)
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
processInputStream()
}
} else if eventCode == .errorOccurred {
disconnectStream(aStream.streamError as NSError?)
} else if eventCode == .endEncountered {
disconnectStream(nil)
}
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: NSError?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
connected = false
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(Data(bytes: buffer, count: length))
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
connected = true
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
if code != httpSwitchProtocolCode {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString {
if acceptKey.length > 0 {
return 0
}
}
}
return -1
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1011 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(errorWithDetail("connection closed by server", code: closeCode))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data = Data(bytes: baseAddress+offset, count: Int(len))
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(errorWithDetail(closeReason, code: closeCode))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
s.onPong?(pongData)
s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
} else if response.code == .textFrame {
let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue)
if str == nil {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str! as String)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Create an error
*/
private func errorWithDetail(_ detail: String, code: UInt16) -> NSError {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: Error?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.outputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error as NSError?)
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
connected = false
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
writeQueue.cancelAllOperations()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
-856
View File
@@ -1,856 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2015 Dalton Cherry.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
import Security
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
public enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
public static let ErrorDomain = "WebSocket"
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : [String]?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((NSData) -> Void)?
public var onPong: ((Void) -> Void)?
public var headers = [String: String]()
public var voipEnabled = false
public var selfSignedSSL = false
public var security: SSLSecurity?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var timeout = 5
public var isConnected :Bool {
return connected
}
public var currentURL: NSURL {return url}
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var connected = false
private var isCreated = false
private var writeQueue = NSOperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [NSData]()
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private let mutex = NSLock()
private let notificationCenter = NSNotificationCenter.defaultCenter()
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
//the shared processing queue used for all websocket
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
//used for setting protocols.
public init(url: NSURL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
///Connect to the websocket server on a background thread
public func connect() {
guard !isCreated else { return }
didDisconnect = false
isCreated = true
createHTTPRequest()
isCreated = false
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
*/
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
switch forceTimeout {
case .Some(let seconds) where seconds > 0:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .None:
writeError(CloseCode.Normal.rawValue)
default:
self.disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func writeString(str: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func writeData(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .Ping, writeCompletion: completion)
}
//private method that starts the connection
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if ["wss", "https"].contains(url.scheme) {
port = 443
} else {
port = 80
}
}
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
}
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
addHeader(urlRequest, key: key, val: value)
}
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest, Int(port!))
}
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ["wss", "https"].contains(url.scheme) {
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if selfSignedSSL {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue)
inStream.open()
outStream.open()
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
let bytes = UnsafePointer<UInt8>(data.bytes)
var out = timeout * 1000000 //wait 5 seconds before giving up
writeQueue.addOperationWithBlock { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) //wait until the socket is ready
out -= 100
if out < 0 {
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
return
} else if outStream.streamError != nil {
return //disconnectStream will be called.
}
}
outStream.write(bytes, maxLength: data.length)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
let possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as String)
if let trust: AnyObject = possibleTrust {
let domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as String)
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
}
if eventCode == .HasBytesAvailable {
if aStream == inputStream {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
}
private func cleanupStream() {
outputStream?.delegate = nil
inputStream?.delegate = nil
if let stream = inputStream {
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
while !inputQueue.isEmpty {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
let combine = NSMutableData(data: fragBuffer)
combine.appendData(data)
work = combine
self.fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
let length = work.length
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{$0 != data}
}
}
//handle checking the inital connection status
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
connected = true
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(s)
s.notificationCenter.postNotificationName(WebsocketDidConnectNotification, object: self)
}
case -1:
fragBuffer = NSData(bytes: buffer, length: bufferLen)
break //do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 //was unable to find the full TCP header
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
if code != 101 {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let acceptKey = headers[headerWSAcceptName] as? NSString {
if acceptKey.length > 0 {
return 0
}
}
}
return -1
}
///read a 16 bit big endian value from a buffer
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
///read a 64 bit big endian value from a buffer
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
///write a 16 bit big endian value to a buffer
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
///write a 64 bit big endian value to a buffer
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/// Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
@warn_unused_result
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
let baseAddress = buffer.baseAddress
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = NSData(buffer: buffer)
return emptyBuffer
}
if let response = response where response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.appendData(NSData(bytes: baseAddress, length: len))
processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .Pong {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .ConnectionClose || receivedOpcode == .Ping)
if !isControlFrame && (receivedOpcode != .BinaryFrame && receivedOpcode != .ContinueFrame &&
receivedOpcode != .TextFrame && receivedOpcode != .Pong) {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
writeError(errCode)
return emptyBuffer
}
if receivedOpcode == .ConnectionClose {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
code = WebSocket.readUint16(baseAddress, offset: offset)
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = baseAddress + offset
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
doDisconnect(errorWithDetail("connection closed by server", code: code))
writeError(code)
return emptyBuffer
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += sizeof(UInt64)
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += sizeof(UInt16)
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = NSData(bytes: baseAddress, length: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
let data: NSData
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: baseAddress+offset, length: Int(len))
}
if receivedOpcode == .Pong {
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onPong?()
s.pongDelegate?.websocketDidReceivePong(s)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .ContinueFrame {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("first frame can't be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .ContinueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.appendData(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
processResponse(response)
}
let step = Int(offset+numericCast(len))
return buffer.fromOffset(step)
}
}
/// Process all messages in the buffer if possible.
private func processRawMessagesInBuffer(pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = NSData(buffer: buffer)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
if canDispatch {
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
}
}
} else if response.code == .BinaryFrame {
if canDispatch {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onData?(data)
s.delegate?.websocketDidReceiveData(s, data: data)
}
}
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = [String: String]()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperationWithBlock { [weak self] in
//stream isn't ready, let's wait
guard let s = self else { return }
var offset = 2
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = s.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += sizeof(UInt16)
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += sizeof(UInt64)
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for i in 0..<dataLength {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
let len = outStream.write(writeBuffer, maxLength: offset-total)
if len < 0 {
var error: NSError?
if let streamError = outStream.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = s.errorWithDetail("output stream error during write", code: errCode)
}
s.doDisconnect(error)
break
} else {
total += len
}
if total >= offset {
if let queue = self?.queue, callback = writeCompletion {
dispatch_async(queue) {
callback()
}
}
break
}
}
}
}
///used to preform the disconnect delegate
private func doDisconnect(error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
connected = false
guard canDispatch else {return}
dispatch_async(queue) { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(s, error: error)
let userInfo = error.map({ [WebsocketDisconnectionErrorKeyName: $0] })
s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo)
}
}
deinit {
mutex.lock()
readyToWrite = false
mutex.unlock()
cleanupStream()
}
}
private extension NSData {
convenience init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress, length: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress.advancedBy(offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)