Compare commits

...
841 Commits
Author SHA1 Message Date
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 Little 05c0874f32 Merge pull request #408 from socketio/development
Development
2016-06-24 02:41:22 -04:00
Erik 2e5442d386 unknown message isn't fatal 2016-06-24 02:35:18 -04:00
Erik f9ae0cfdb3 bump version 2016-06-24 02:22:23 -04:00
Erik 7ad90de184 Merge branch 'master' into development
* master:
  bump version
2016-06-24 02:21:54 -04:00
Erik 4383ddfe65 notify client when engine disconnects 2016-06-24 02:21:25 -04:00
Erik 2a0ce72792 small swift 3 changes 2016-06-22 10:04:27 -04:00
Erik 45373ad680 bump version 2016-06-17 10:05:20 -04:00
Erik Little 5ced8a5a9e Merge pull request #399 from socketio/development
Development
2016-06-17 10:03:50 -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 6fd3294fba Revert "swift 2.3"
This reverts commit bfa163f3c2.
2016-06-14 19:41:18 -04:00
Erik bfa163f3c2 swift 2.3 2016-06-14 19:37:27 -04:00
Erik d8826a9db3 allow access from objective-c 2016-06-14 16:19:40 -04:00
Erik b9e3de2d50 add documentation 2016-06-14 16:13:01 -04:00
Erik e163598ee6 add option for sslsecurity 2016-06-14 16:11:37 -04:00
Erik 2c059e1a6e log server 2016-06-14 09:38:35 -04:00
Erik 6f21059ff8 work on experimental manager 2016-06-11 12:38:35 -04:00
Erik 523ced2f9a merge development 2016-06-09 09:37:26 -04:00
Erik 58a5a17464 Move websocket to subfolder, don't combine websocket files 2016-06-09 09:28:40 -04:00
Erik cb0a6f5460 rename method 2016-06-07 13:20:23 -04:00
Erik b919d3e411 hopefully fix socket.io/socket.io-client-swift#374 2016-06-07 13:12:34 -04:00
Erik 02f30a81dd fix test 2016-06-06 16:25:37 -04:00
Erik e57bcba47d encoding should already be done at this point 2016-06-06 15:41:19 -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 71f9058723 refactors: refactor creating packet string, various other refactors 2016-05-30 21:42:00 -04:00
Erik 0564ded492 don't check type on each pass through loop 2016-05-25 08:47:50 -04:00
Erik ff48d3a186 Merge branch 'master' into development
* master:
  Fix crash if error contains formatting strings.
2016-05-25 08:20:03 -04:00
Erik Little 4fa3225cba Merge pull request #372 from ATLCTO/master
Fix crash if error contains formatting strings.
2016-05-25 08:19:28 -04:00
Erik ee24943c72 remove ios tests folder 2016-05-24 11:26:50 -04:00
Erik Little 31e4c60db8 Merge pull request #373 from socketio/development
Development
2016-05-24 11:18:31 -04:00
Erik ab536e2279 bump version 2016-05-24 11:08:22 -04:00
Patrick Childers 3d47ff469f Fix crash if error contains formatting strings. 2016-05-23 17:03:51 -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 3401414430 bump websocket 2016-05-17 22:35:33 -04:00
Erik 50216647ca refactors 2016-05-11 13:40:45 -04:00
Erik 98063c8bf7 refactoring 2016-05-06 12:48:33 -04:00
Erik 9747cc4ddc allow reconnects after disconnecting 2016-05-06 10:17:43 -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 7e23597351 no longer need swiftregex 2016-05-05 13:19:26 -04:00
Erik 437c0880e8 don't use placeholder strings for binary 2016-05-05 13:12:05 -04:00
Erik Little c237197b8c Merge pull request #362 from socketio/development
Development
2016-05-05 09:21:29 -04:00
Erik 4ea3f40ca7 bump version 2016-05-05 08:59:00 -04:00
Erik a24b54c18f Merge branch 'master' into development
* master:
  bump version
2016-05-05 08:57:55 -04:00
Erik Little 2377c8b45f Merge pull request #363 from yannickl/development
Adding test case for issue #361
2016-05-04 12:56:59 -04:00
Yannick Loriot e02ca23d14 Add test case #361 2016-05-04 18:35:56 +02:00
Erik 18285f5401 small style changes 2016-05-04 09:44:01 -04:00
Erik 1c80cc7e4c newline 2016-05-04 09:34:02 -04:00
Erik 0959dd35d7 change author name 2016-05-04 09:30:55 -04:00
Erik 5d23270d70 Merge branch 'development' of https://github.com/socketio/socket.io-client-swift into development
* 'development' of https://github.com/socketio/socket.io-client-swift:
  Minor refactoring to make the build of the query more readable
  Fixing url encoding for connect params
2016-05-04 09:27:10 -04:00
Erik 2b4b5bf407 move comment 2016-05-04 09:27:08 -04:00
Erik Little 84cb635f11 Merge pull request #361 from yannickl/development
Fixing url encoding for connect params
2016-05-04 09:26:34 -04:00
Yannick Loriot 119b479be2 Minor refactoring to make the build of the query more readable 2016-05-04 13:03:40 +02:00
Yannick Loriot 9ff90f511e Fixing url encoding for connect params 2016-05-04 12:56:14 +02:00
Erik 82e7882497 add rest of emitWithAck for objc test 2016-04-27 18:32:38 -04:00
Erik 8e1434e63b change status names, execute engine connect on emitQueue 2016-04-27 14:38:11 -04:00
Erik 44ee94d2ac refactors 2016-04-26 15:28:08 -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 6efeb7d5b2 expose ws 2016-04-16 11:04:26 -04:00
Erik e1865e3f94 rename file 2016-04-16 10:43:20 -04:00
Erik 1b4b571be6 bump version 2016-04-11 18:58:02 -04:00
Erik Little c9f653ef2c Merge pull request #344 from socketio/development
Development
2016-04-11 18:55:27 -04:00
Erik 3073130598 change to how server gives id 2016-04-11 18:51:22 -04:00
Erik 376e31bfca merge development and fix tests 2016-04-10 14:15:35 -04:00
Erik ed3d49001f bump websocket version 2016-04-10 13:59:21 -04:00
Erik 4ee196c5fb add default value to namespace in socketparsable 2016-04-04 11:28:20 -04:00
Erik baca9fc8da small refactors 2016-03-31 21:31:24 -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 1a5ac74984 Merge branch 'master' into development
* master:
  set targetted device family to 3
  use 7.3 image
2016-03-25 17:02:52 -04:00
Erik Little 6c779e84d2 Merge pull request #335 from craigkj312/master
actual fix for carthage
2016-03-25 17:01:53 -04:00
Kyle Craig 293d71bf97 set targetted device family to 3 2016-03-25 15:54:57 -05: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
Erik 2f1f77141e add test for objc api 2016-03-25 10:00:14 -04:00
Erik d4c01183ab style 2016-03-25 09:48:04 -04:00
Erik 5d81377e0a use 7.3 image 2016-03-24 14:46:32 -04:00
Erik 8f8d5acdba use 7.3 image 2016-03-24 14:17:49 -04:00
Erik a0167ae213 remove deprecated methods 2016-03-23 13:39:22 -04:00
Erik 4f5837afa7 don't need objc on this method anymore 2016-03-22 10:15:09 -04:00
Erik 718caba9d9 remove nstimer 2016-03-22 09:56:56 -04:00
Erik Little 2919d4a5ce Merge pull request #330 from socketio/development
Development
2016-03-22 09:06:13 -04:00
Erik a53b7167b6 update version and readme 2016-03-22 09:05:57 -04:00
Erik 6c6b4f32c9 Update for swift 2.2 2016-03-22 09:00:27 -04:00
Erik 3a842469ec fix log placement 2016-03-16 13:13:22 -04:00
Erik 596a499041 work on fixing reconnect() 2016-03-11 13:41:09 -05:00
Erik 76a572e735 refactor reconnect 2016-03-11 13:03:40 -05:00
Erik 6da9463c8d whitespace 2016-03-03 10:11:08 -05:00
Erik 2f7a5405b0 add check for fast upgrade 2016-03-03 09:59:33 -05:00
Erik 62131ef904 make sure we don't handle poll messages if we aren't polling 2016-03-03 09:57:39 -05:00
Erik 5976ef1752 bump websocket version 2016-02-27 19:43:21 -05:00
Erik 16e0bf6319 bump version 2016-02-25 19:13:08 -05:00
Erik Little 11c0ac249b Merge pull request #317 from jtjacka/master
fix timeoutAfter handler always close connection
2016-02-25 19:11:33 -05:00
jtjacka 1e96d7982d fix timeoutAfter handler always close connection 2016-02-25 16:06:08 -08:00
Erik 2f4c942dcf use connect/disconnect for engine 2016-02-23 10:33:14 -05:00
Erik 70283acc1f add messages to deprecated methods 2016-02-17 14:27:48 -05:00
Erik e16914f7d6 remove unused param 2016-02-17 14:15:15 -05:00
Erik c795f9fb25 refactor socketpacket 2016-02-17 14:09:05 -05:00
Erik 12f9207d8a rename waitingData to waitingPackets 2016-02-16 17:03:00 -05:00
Erik 0bf27b8c49 bump version 2016-02-16 14:28:18 -05:00
Erik 6ac96f8d91 modify test 2016-02-16 14:27:18 -05:00
Erik f7397155b6 add test cases 2016-02-16 14:26:21 -05:00
Erik 70d59ea9d4 fix quotes in strings 2016-02-16 14:21:10 -05:00
Erik 7fe2dc2c70 bump version 2016-02-15 10:48:24 -05:00
Erik fe9ee602e7 add option for toggling double encoding utf8 2016-02-15 10:43:21 -05:00
Erik 6fa5ce9168 don't call connect timeout if status is closed 2016-02-14 20:16:01 -05:00
Erik 43b2d4646f bump websocket version 2016-02-12 08:45:44 -05:00
Erik 0f70079382 fix possible race condition 2016-02-11 09:36:36 -05:00
Erik 750ba138e1 bump version 2016-02-05 14:05:50 -05:00
Erik 3e8ca90e3a don't fatalerror 2016-02-05 13:09:26 -05:00
Erik 2a25027077 change to weak self 2016-02-04 15:59:39 -05:00
Erik 15dfba42a7 bump version 2016-02-04 10:15:50 -05:00
Erik 76ef3596f0 possible fix for socketio/socket.io-client-swift#279 2016-02-01 21:56:49 -05:00
Erik 8e208b1c66 bump websocket version again 2016-01-29 16:57:50 -05:00
Erik 8c9a93f79d bump version 2016-01-29 16:54:16 -05:00
Erik cf651b8a00 Don't add newlines to base64 encoded stuff. Fixes nuclearace/Socket.IO-Client-Swft#105 2016-01-29 16:53:19 -05:00
Erik b8307b6b27 refactor test 2016-01-29 13:08:41 -05:00
Erik fe3599d1fe add test for parsing double encoded utf8 2016-01-29 13:06:56 -05:00
Erik 8d22de967e bump websocket version 2016-01-28 09:09:29 -05:00
Erik ff9c1bb67b bump version 2016-01-27 16:07:50 -05:00
Erik c92e146dfc small tweaks 2016-01-27 16:00:36 -05:00
Erik d71f81745e move websocketurl plus sid to computed property 2016-01-26 14:17:11 -05:00
Erik 228c0c7c9b small readme change 2016-01-26 11:28:32 -05:00
Erik Little d36ef10404 Merge pull request #289 from socketio/nsurl-based
Nsurl based
2016-01-26 11:24:19 -05:00
Erik c5c00510e5 remove unused property 2016-01-26 11:03:32 -05:00
Erik e38c4081ec comments and style 2016-01-26 10:51:53 -05:00
Erik 5060f90a79 we need to update the urls if connectparams changes 2016-01-25 19:13:17 -05:00
Erik 57670ec613 move connectparams to the engine 2016-01-25 19:02:47 -05:00
Erik 3f57c7e0a9 add default urls 2016-01-25 18:48:21 -05:00
Erik efe0d01592 update docs 2016-01-25 18:23:15 -05:00
Erik f9c665a542 for whatever reason I was able trigger a race condition because of the last commit 2016-01-25 17:23:57 -05:00
Erik b67b6abbdf engine polling to nsurl 2016-01-25 16:21:52 -05:00
Erik d912796fa5 engine websocket url to nsurl 2016-01-25 15:52:54 -05:00
Erik c9ac69f408 first pass at socketio/socket.io-client-swift#288 2016-01-25 14:55:58 -05:00
Erik cc7d96e3d5 remove trailing / from urls 2016-01-25 10:46:03 -05:00
Erik bf1104443a make engine send internal 2016-01-24 11:31:04 -05:00
Erik adf8692234 change log message 2016-01-22 18:16:30 -05:00
Erik 94f02e567a bump version 2016-01-21 10:07:52 -05:00
Erik 4eca685dc2 fix nuclearace/Socket.IO-Client-Swift#103 2016-01-21 10:04:55 -05:00
Erik 90f512e03b remove disconnect 2016-01-20 14:41:12 -05:00
Erik 7d8b0c89c5 bump version 2016-01-20 14:39:07 -05:00
Erik e45003210f revert to unbroken websocket version 2016-01-20 14:38:13 -05:00
Erik 4d07d2911f bump version 2016-01-18 15:55:18 -05:00
Erik 0d6e4af62f fix websocket bug 2016-01-18 15:54:28 -05:00
Erik 2e6803bd1a bump version 2016-01-18 12:44:37 -05:00
Erik bcb556b66c bump websocket 2016-01-18 10:03:16 -05:00
Erik d8b5293ca1 fix readme 2016-01-17 10:57:17 -05:00
Erik ec2aa703a3 Send close reason to engine 2016-01-17 10:30:34 -05:00
Erik c211ab140d We're always connecting anyway 2016-01-17 10:29:10 -05:00
Erik 5cab7dbb2f changes to swiftregex 2016-01-17 10:10:36 -05:00
Erik 0fc70e8be1 deprecate open() 2016-01-17 09:50:03 -05:00
Erik Little 609ce08351 Merge pull request #278 from socketio/standardize-module-name
Standardize module name
2016-01-17 09:29:33 -05:00
Erik e366e808ae update cocoapods documentation 2016-01-17 09:22:59 -05:00
Erik 03d5f56114 merge master 2016-01-17 08:48:34 -05:00
Erik 2cf448de72 change module name for cocoapods 2016-01-17 08:46:17 -05:00
Erik fb0c6a5612 Revert "is this what changes the cocoapods build name"
This reverts commit 3587c20718.
2016-01-17 08:45:20 -05:00
Erik a9633510ff update readme to reflect close being deprecated 2016-01-16 19:56:03 -05:00
Erik 95d2dce641 bump version 2016-01-16 19:53:00 -05:00
Erik 88b1eb1948 going to remove close() 2016-01-16 19:51:21 -05:00
Erik 67f47ad6fe tweak logging 2016-01-16 17:37:17 -05:00
Erik d6c521123b refactor closing engine 2016-01-16 17:23:07 -05:00
Erik 024384dc82 change close method of engine 2016-01-16 16:40:50 -05:00
Erik ec67056d2a change method signature 2016-01-16 16:38:10 -05:00
Erik 15cfba46bc refactor didError 2016-01-16 15:16:18 -05:00
Erik dbc8b6fadc refactor engine erroring 2016-01-16 15:04:03 -05:00
Erik Little d15fb90950 Merge pull request #280 from socketio/engine-protocol-refactoring
Engine protocol refactoring
2016-01-16 13:07:43 -05:00
Erik e06a792503 add some comments 2016-01-15 19:12:07 -05:00
Erik b202b21d43 remove comment 2016-01-15 17:35:20 -05:00
Erik 443f5c5b22 move declaration of postWait 2016-01-15 14:21:59 -05:00
Erik 3979b36f63 more refactoring 2016-01-15 14:15:50 -05:00
Erik ac460d8023 newline 2016-01-15 13:31:01 -05:00
Erik 731c8a851b first pass at refactoring engine 2016-01-15 13:17:13 -05:00
Erik a299901fa8 why I didn't use contains first idk 2016-01-15 10:05:44 -05:00
Erik 660aed8359 small tweaks 2016-01-15 09:56:53 -05:00
Erik Little 06aafa78ed Merge pull request #277 from leo0307vb/addEngineDidOpen
add new method engineDidOpen in socketEngineClient protocol
2016-01-15 09:54:25 -05:00
leo0307vb 3c9070b3e7 fix engineDidOpen implementation 2016-01-14 17:57:58 -05:00
Erik 3587c20718 is this what changes the cocoapods build name 2016-01-14 16:06:54 -05:00
Erik de3ca964ab work on standardizing module name 2016-01-14 16:01:46 -05:00
leo0307vb 19c68416bb add new method engineDidOpen in socketEngineClient protocol 2016-01-14 14:44:32 -05:00
Erik ee5934de6a bump version 2016-01-13 12:23:30 -05:00
Erik ca67625ed3 remove redundancies 2016-01-03 14:14:42 -05:00
Erik fe02b8eff2 change socketparser into a protocol 2016-01-03 13:11:18 -05:00
Erik 0c8ff90537 change pattern matching syntax 2016-01-03 12:00:37 -05:00
Erik 5068986a50 fix socketio/socket.io-client-swift#233 2016-01-03 11:56:16 -05:00
Erik 4ed4681cc4 change visibility of connectParams 2016-01-03 11:11:58 -05:00
Erik 361cd8fc3b change some methods to use nsurlrequest 2016-01-03 10:12:02 -05:00
Erik 2916ed0f7b cache method isn't implemented 2016-01-03 10:10:41 -05:00
Erik cfa98ea42b remove ++ 2016-01-03 09:55:10 -05:00
Erik 8584b90d3c simplify namespace api 2016-01-02 17:38:19 -05:00
Erik 7acce7d18e small tweaks 2015-12-30 20:14:31 -05:00
Erik 0ebe56d780 remove anonymous function and use named function 2015-12-26 17:22:03 -05:00
Erik 3d8867136d comment some socketpacket methods 2015-12-26 13:38:59 -05:00
Erik bed5ecd23b more pattern matching 2015-12-26 13:18:07 -05:00
Erik 4e5fcff258 use pattern matching 2015-12-26 13:09:24 -05:00
Erik aeb52de72f don't need to keep count manually 2015-12-25 11:28:08 -05:00
Erik ca90938675 refactor socketpacket 2015-12-25 11:24:03 -05:00
Erik 1aacab2567 use testable 2015-12-25 10:22:59 -05:00
Erik a28fda392c move test files 2015-12-25 10:11:00 -05:00
Erik 931382deff refactors 2015-12-25 10:02:09 -05:00
Erik 298817ce5c refactor 2015-12-23 14:00:06 -05:00
Erik Little 8cf3aebf9f Update README.md 2015-12-22 14:38:04 -05:00
Erik 75fc013f92 document spm 2015-12-22 14:35:31 -05:00
Erik 44c5591646 bump version 2015-12-22 14:12:56 -05:00
Erik 8e0d03b28c add basic package.swift file 2015-12-22 13:43:07 -05:00
Erik 7b1f72852f bump version 2015-12-20 15:42:40 -05:00
Erik 97d4f3f527 fix encoding of postWait messages sent over websocket 2015-12-20 15:36:42 -05:00
Erik d94a1901ca refactor. Remove var from methods and pattern matching 2015-12-20 15:01:28 -05:00
Erik fff2f29c55 remove extra stuff 2015-12-12 13:36:43 -05:00
Erik 57d1f3c4b4 bump websockets 2015-12-12 13:35:28 -05:00
Erik Little 499c0d6824 Merge pull request #255 from NachoSoto/deployment-target
Explicitly setting deployment target for to watchOS 2.0 and tvOS 9.0
2015-12-09 19:32:26 -05:00
NachoSoto 85cf6c48b1 Explicitly setting deployment target for to watchOS 2.0 and tvOS 9.0
Before this change, they would default to `watchOS 2.1` and `tvOS 9.1` in `Xcode 7.2`.
2015-12-10 00:20:05 +00:00
Erik 5848516c4e bump version 2015-12-08 20:17:39 -05:00
Erik 238d3cb338 add option for selfSigned 2015-12-08 20:15:54 -05:00
Erik 275c873880 remove mutable parameter 2015-12-07 15:09:07 -05:00
Erik 2ccaa4351a bump websocket 2015-12-07 14:46:27 -05:00
Erik Little c642017f4b Merge pull request #250 from socketio/off-with-id
Off with id
2015-12-05 15:14:17 -05:00
Erik 7b11e7c3e0 documentation 2015-12-04 10:08:47 -05:00
Erik 6e5b95be31 fix nuclearace/Socket.IO-Client-Swift#97 2015-12-04 10:03:01 -05:00
Erik ccad13a1ed use pattern matching, thanks @NachoSoto 2015-12-03 21:01:43 -05:00
Erik bb26ae8637 indentation 2015-12-03 20:49:17 -05:00
Erik b9fd6c9d5b document new option 2015-12-03 14:36:57 -05:00
Erik f001b8340c update readme 2015-12-03 14:26:28 -05:00
Erik 9b67549d25 Merge branch 'engine-refactoring'
* engine-refactoring:
  rename source directory
2015-12-03 14:25:47 -05:00
Erik e2f89d82e4 rename source directory 2015-12-03 14:25:23 -05:00
Erik Little 9c1a3edeb9 Merge pull request #248 from socketio/engine-refactoring
Engine refactoring
2015-12-03 14:16:24 -05:00
Erik 04d49fe7cb fix socketio/socket.io-client-swift#246 2015-12-02 12:46:54 -05:00
Erik c74858fd5d Revert "add case for opening poll"
This reverts commit 0acb7421cc.
2015-12-02 12:32:31 -05:00
Erik 0acb7421cc add case for opening poll 2015-12-02 12:16:35 -05:00
Erik 57b252fa7d refactor engine, don't re-add engine on reconnect, other improvements 2015-12-01 15:17:18 -05:00
Erik 87e12fd284 bump ws 2015-11-24 13:29:49 -05:00
Erik 0470647d87 error on unknown engine messages 2015-11-19 10:15:01 -05:00
Erik 80a734e95f fix nuclearace/Socket.IO-Client-Swift#92 2015-11-18 08:19:48 -05:00
Erik c26adae13c reset logging when socket is deinit 2015-11-17 13:29:14 -05:00
Erik 76375bbcf3 how do I logic 2015-11-17 12:41:48 -05:00
Erik 6199c2f914 refactoring 2015-11-17 12:37:31 -05:00
Erik e0c794cb9f refactoring 2015-11-17 12:34:22 -05:00
Erik db63aa63c2 bump version 2015-11-16 13:24:08 -05:00
Erik 9aec259d67 refactor again 2015-11-15 11:46:02 -05:00
Erik 6e21fba469 refactor 2015-11-15 11:43:05 -05:00
Erik 38e08f17a2 remove unused field 2015-11-15 10:51:09 -05:00
Erik 71c78e1e12 clean up api again 2015-11-10 20:02:58 -05:00
Erik b35004ef60 clean up some internal apis 2015-11-09 11:41:06 -05:00
Erik cf14eb27a3 emit error when trying to emit when not connected 2015-11-09 11:33:41 -05:00
Erik 0de8a65ff4 move Logger to static variable 2015-11-04 17:19:45 -05:00
Erik fe21fcc7e1 style 2015-11-03 12:23:14 -05:00
Erik 4be7bb0079 update readme 2015-11-03 09:33:49 -05:00
Erik da5977ac31 bump version 2015-11-02 17:37:20 -05:00
Erik bbb383da58 fix secure connections 2015-11-02 17:36:35 -05:00
Erik Little c818ed2c10 Merge pull request #227 from dickverbunt/patch-1
Supporting tvOS for Cocoapods
2015-11-02 12:50:38 -05:00
Dick Verbunt 6e54ac4534 Supporting tvOS for Cocoapods 2015-10-31 22:06:10 +01:00
Erik a87214cf06 refactor client options 2015-10-30 13:09:56 -04:00
Erik 8c405cee88 refactor 2015-10-29 19:15:24 -04:00
Erik 0b6cece96b refactor client dispatch queues 2015-10-29 19:10:38 -04:00
Erik 9633bea018 update README 2015-10-29 18:36:29 -04:00
Erik d808ae18d2 bump version 2015-10-29 18:30:47 -04:00
Erik f6dabf8f8e set secure for legacy api 2015-10-29 18:29:56 -04:00
Erik 47fd0e386f further decouple engine and client 2015-10-29 18:25:45 -04:00
Erik Little 9deb5a06a6 Merge pull request #222 from NachoSoto/tvos-2
Added target and scheme for tvOS
2015-10-22 22:48:51 -04:00
NachoSoto 8f27b0d021 Added target and scheme for tvOS
Fixes #221

```
Test Suite 'SocketIO-tvOSTests.xctest' passed at 2015-10-22 17:21:34.436.
	 Executed 56 tests, with 0 failures (0 unexpected) in 0.817 (0.867) seconds
Test Suite 'All tests' passed at 2015-10-22 17:21:34.437.
	 Executed 56 tests, with 0 failures (0 unexpected) in 0.817 (0.868) seconds
````
2015-10-23 00:22:35 +00:00
Erik e137e66592 turn off bitcode on os x 2015-10-22 09:57:06 -04:00
Erik bba966a125 add option for setting WebSocket.voipEnabled 2015-10-21 20:51:19 -04:00
Erik 0579e7ec19 always set a session 2015-10-21 15:16:22 -04:00
Erik aee0382cbc bump version 2015-10-21 15:09:05 -04:00
Erik 9abf2e77e0 use socketioclientoptions for engine 2015-10-21 15:07:00 -04:00
Erik 0dd3def2e4 don't need extra inits in enums 2015-10-21 11:16:27 -04:00
Erik c5d70b4888 change order of closing 2015-10-20 12:33:03 -04:00
Erik ee38630468 bump version 2015-10-20 12:28:55 -04:00
Erik 5a65efe526 close engine when client is being released 2015-10-20 12:28:18 -04:00
Erik 02971e14c2 always close fast. Don't handle acks after close 2015-10-19 16:40:09 -04:00
Erik ea7e60cde2 bump version 2015-10-19 11:33:44 -04:00
Erik Little 83cee796d8 Merge pull request #212 from socketio/better-options
Better options
2015-10-19 11:28:25 -04:00
Erik 86bd271a9f remove extra letter 2015-10-18 18:27:52 -04:00
Erik 6e31f54e88 fix socketio/socket.io-client-swift#216 2015-10-18 18:27:12 -04:00
Erik b97574e28a don't typealias 2015-10-18 16:55:33 -04:00
Erik ab56b58b2d rename external variable 2015-10-18 16:42:34 -04:00
Erik 8e2f478989 Make static method an instance method 2015-10-18 16:36:01 -04:00
Erik c99f9a6b97 make sure wait is positive 2015-10-18 16:33:31 -04:00
Erik 45b5852e50 refactor 2015-10-18 16:31:46 -04:00
Erik c608bf8286 Do some black magic to turn case into lower camel case 2015-10-18 15:48:31 -04:00
Erik 6c6084705e rename file 2015-10-18 15:36:06 -04:00
Erik 885965c5bc update examples 2015-10-18 15:18:25 -04:00
Erik ac228ccede update readme 2015-10-18 15:16:44 -04:00
Erik 7bc8cd01e8 remove unsafe 2015-10-18 14:58:52 -04:00
Erik b9e05286a2 even more type safe solution, idea from @lightsprint09 2015-10-18 14:52:46 -04:00
Erik a5db43b834 add comments 2015-10-17 14:58:47 -04:00
Erik 7382030dff there's a typealias for a reason 2015-10-17 14:54:09 -04:00
Erik 40ac53844d mess around with a more type safe way to set options 2015-10-17 14:49:41 -04:00
Erik 7f443faf92 don't couple to WebSocket in enginespec 2015-10-16 14:59:53 -04:00
Erik a6c700230d don't need two inits 2015-10-16 12:47:33 -04:00
Erik aa368f92cf don't force unwrap in fixutf 2015-10-16 12:39:45 -04:00
Erik 28ae7a8240 change access levels 2015-10-16 12:28:42 -04:00
Erik Little e07ed93c0b Merge pull request #194 from socketio/travis
Test refactors
2015-10-15 15:37:11 -04:00
Erik 17fb142083 remove old stuff. change test name 2015-10-15 15:29:03 -04:00
Erik 66674aae78 start work on engine tests 2015-10-15 15:15:18 -04:00
Erik 395dc48287 Merge branch 'master' into travis
* master:
  bump version
  try and fix carthage builds
  bump version:
2015-10-15 14:09:46 -04:00
Erik 1648a51b6f bump version 2015-10-15 14:06:28 -04:00
Erik ad7043c918 try and fix carthage builds 2015-10-15 14:01:52 -04:00
Erik 48672d8df3 bump version: 2015-10-15 13:50:05 -04:00
Erik d657538214 refactor 2015-10-15 13:49:03 -04:00
Erik a231104c15 refactor 2015-10-14 13:21:11 -04:00
Erik ab8de6932c Merge branch 'master' into travis
* master:
  change code signing
2015-10-13 12:52:03 -04:00
Erik c101a04845 change code signing 2015-10-13 12:51:46 -04:00
Erik 3d06b7dbad merge master 2015-10-13 12:32:15 -04:00
Erik f57786ad5b remove debug print 2015-10-13 12:28:52 -04:00
Erik 7ff1d327de Fix socketio/socket.io-client-swift#203 2015-10-13 12:28:02 -04:00
Erik 99e2da235a add test for multiple binary 2015-10-12 12:41:55 -04:00
Erik a20a0f14f3 fix packet type 2015-10-12 11:29:17 -04:00
Erik 0e478085a3 add binary event test 2015-10-12 11:25:56 -04:00
Erik 61eda5971e rename test 2015-10-11 13:12:56 -04:00
Erik 32e1f55394 work on side effect tests 2015-10-11 13:11:18 -04:00
Erik a88a859750 rename socketnamespaceemittest 2015-10-11 12:08:17 -04:00
Erik aaefdd0a2e change tests to socketpacket tests 2015-10-11 12:07:24 -04:00
Erik 4c7a09cc8e add emitwithack tests 2015-10-07 14:31:35 -04:00
Erik 90c7c9aadc add some more tests 2015-10-07 12:55:43 -04:00
Erik 84499d4c21 start working on tests 2015-10-07 12:01:55 -04:00
Erik bfe54f8df7 start work on seperating socket client and engine so they can be tested 2015-10-07 11:16:35 -04:00
Erik Little 18a227e591 Merge pull request #201 from tbaranes/master
Add CocoaSeeds installation
2015-10-07 10:48:50 -04:00
Tom Baranes 6d49c37fb8 Fix syntax highlighting 2015-10-07 15:27:40 +02:00
Tom Baranes a0c213364d Add CocoaSeeds installation 2015-10-07 08:49:49 +02:00
Erik Little 3c79bd0a75 Merge pull request #198 from NachoSoto/bitcode
Enabled Bitcode
2015-10-05 09:48:41 -04:00
NachoSoto a11533b61f Enabled Bitcode 2015-10-05 05:03:55 +00:00
Erik 8acd32324e tweak to connect timeout 2015-10-01 15:25:41 -04:00
Erik b65dfec6b0 tweak to connect timeout 2015-10-01 15:25:17 -04:00
Erik 1e07070798 tweak to travis 2015-10-01 13:17:18 -04:00
Erik 927ab155e3 merge master 2015-10-01 13:01:13 -04:00
Erik de20099c07 style 2015-10-01 12:59:27 -04:00
Erik 877db516c2 fix socketio/socket.io-client-swift#197 2015-10-01 09:53:20 -04:00
Erik 4dd882b8ad bump version 2015-09-30 21:08:23 -04:00
Erik ccc3745bb8 fix for socketio/socket.io-client-swift#196 2015-09-30 18:38:39 -04:00
Erik 718dc27089 tweaks to polling 2015-09-30 09:26:23 -04:00
Erik 798d8a62ae bump version 2015-09-29 08:52:46 -04:00
Erik 9241bf869f fix another crash case 2015-09-28 20:52:03 -04:00
Erik 7573355731 style 2015-09-28 20:47:31 -04:00
Erik f3b4c0eba3 Revert "tweaks to testing"
This reverts commit d2f39b163a.
2015-09-28 15:46:25 -04:00
Erik d2f39b163a tweaks to testing 2015-09-28 15:39:32 -04:00
Erik b8ab80bdf1 bump time 2015-09-28 14:43:12 -04:00
Erik 66455f3e1b add namespace polling ack test 2015-09-28 14:37:51 -04:00
Erik 5d867f4f65 add namespace polling emit test 2015-09-28 14:36:03 -04:00
Erik 166d59341c bump websocket 2015-09-28 13:44:16 -04:00
Erik 1ad87bdb0d add polling ack tests 2015-09-28 13:41:05 -04:00
Erik 14dc5957fc add tests for just polling 2015-09-28 12:57:29 -04:00
Erik c757ede90e don't request if closed 2015-09-28 12:42:02 -04:00
Erik e99030846f don't request if closed 2015-09-28 12:41:47 -04:00
Erik 3f8941d35b Merge branch 'master' into travis
* master:
  bump websocket
  bump version
2015-09-26 16:55:38 -04:00
Erik a005646054 bump websocket 2015-09-26 16:49:34 -04:00
Erik 3025911502 tweaks 2015-09-26 12:30:12 -04:00
Erik 3791b9c112 isolate namespace and regular sockets 2015-09-26 11:56:24 -04:00
Erik 39135c089b don't need this 2015-09-25 16:47:30 -04:00
Erik bd5e2db98a oops 2015-09-25 14:49:34 -04:00
Erik 4531d2e1a1 still fiddling with travis 2015-09-25 14:46:47 -04:00
Erik 5772f8fb4f Revert "Still messing with travis"
This reverts commit b336f0e267.
2015-09-25 14:43:10 -04:00
Erik b336f0e267 Still messing with travis 2015-09-25 14:33:31 -04:00
Erik d647c53122 travis pls 2015-09-25 13:34:56 -04:00
Erik f933b7addc bump version 2015-09-25 12:45:00 -04:00
Erik 288c04e629 Merge branch 'master' into travis
* master:
  fix namespaces
  bump version
2015-09-25 12:42:30 -04:00
Erik 3754cd2c2d fix namespaces 2015-09-25 12:42:22 -04:00
Erik 20b28b2f43 bump version 2015-09-25 11:57:31 -04:00
Erik a5d40c4479 merge master 2015-09-25 11:36:26 -04:00
Erik 31fbe1040d remove tv, check tv branch 2015-09-25 11:31:54 -04:00
Erik c0afc006e3 Revert "remove tv support, it causes some problems"
This reverts commit ded625aaef.
2015-09-25 11:29:41 -04:00
Erik fe0d5d835f don't sign mac 2015-09-25 11:25:20 -04:00
Erik ded625aaef remove tv support, it causes some problems 2015-09-25 11:21:37 -04:00
Erik 54e0b6c189 switch to mac tests 2015-09-25 11:20:27 -04:00
Erik 72ed7d4be8 travis pls 2015-09-25 10:45:32 -04:00
Erik b9c01ce614 try and fix xctool and node 2015-09-25 10:33:41 -04:00
Erik faaa0473d9 Is it already upgraded? 2015-09-25 10:16:38 -04:00
Erik 195f04c982 see about fixing travis 2015-09-25 10:14:13 -04:00
Erik 0eeecd84ce tweaks to socketengine 2015-09-25 10:13:23 -04:00
Erik Little 4ae6489230 Merge pull request #192 from socketio/either
Either
2015-09-25 09:29:02 -04:00
Erik 0ebbf3f0cd Don't need optionals here 2015-09-24 15:01:06 -04:00
Erik 12b312de57 tweaks 2015-09-24 14:48:33 -04:00
Erik bb518ac1a4 See what using an Either type would look like 2015-09-24 14:40:16 -04:00
Erik 13176f149c bump version 2015-09-22 16:26:11 -04:00
Erik 3e53228e36 remove print 2015-09-21 14:45:48 -04:00
Erik Little e2cd910fa7 Merge pull request #186 from lightsprint09/travis-test-imporvements
Travis test imporvements
2015-09-19 16:41:35 -04:00
Lukas Schmidt 21ac65733f back to xcodebuild 2015-09-19 21:01:06 +02:00
Lukas Schmidt 6ab7455a08 valid yaml 2015-09-19 20:57:52 +02:00
Lukas Schmidt 7a146bf6ac try using xctool 2015-09-19 20:50:12 +02:00
Lukas Schmidt 0d7d319cc3 remove remote test server option 2015-09-19 20:42:07 +02:00
Lukas Schmidt 14b0022fdc remove node dependencies 2015-09-19 20:41:58 +02:00
Lukas Schmidt 9c16ffade8 xctool not working 2015-09-19 20:32:25 +02:00
Lukas Schmidt 30c1a4df97 parallel test server 2015-09-19 20:28:44 +02:00
Erik 492ae89344 small tweak to readme 2015-09-18 13:31:00 -04:00
Erik Little 7bdf80d133 Merge pull request #185 from socketio/api-cleanup
Api cleanup
2015-09-18 13:29:41 -04:00
Erik 01b88f8e37 fix readme 2015-09-18 13:16:09 -04:00
Erik 9860452814 don't use operator 2015-09-18 13:09:22 -04:00
Erik 835e1c2262 I don't see a need for unowned 2015-09-18 12:54:09 -04:00
Erik ba7ffe6d26 space 2015-09-18 12:46:55 -04:00
Erik 6ed90a3e60 clean up once 2015-09-18 12:45:35 -04:00
Erik d2d9c49414 no need to force unwrap 2015-09-18 12:41:27 -04:00
Erik 4c033f81d6 make final class 2015-09-18 12:31:55 -04:00
Erik b0cf8d2c40 tweaks 2015-09-18 12:28:28 -04:00
Lukas Schmidt 1a48adb03d move out of server dir 2015-09-18 18:23:49 +02:00
Lukas Schmidt 9a39524ba2 npm install before running test server 2015-09-18 18:19:05 +02:00
Lukas Schmidt 5b6b36a2dc travis test 2015-09-18 18:14:12 +02:00
Lukas Schmidt 198f24c684 clean code 2015-09-18 18:09:35 +02:00
Erik f464eba995 tweaks 2015-09-18 11:52:35 -04:00
Erik 0e791176bd fix readme 2015-09-18 11:36:11 -04:00
Erik 243a750377 fix readme 2015-09-18 11:35:29 -04:00
Lukas Schmidt 6cffbc2404 Merge remote-tracking branch 'socketio/master' 2015-09-18 17:34:39 +02:00
Erik a56227d08a merge master 2015-09-18 11:33:07 -04:00
Erik 0233bce881 tweaks to closing 2015-09-18 09:27:14 -04:00
Erik 456406416a other init doesn't exist anymore 2015-09-18 09:02:18 -04:00
Erik 99ed93038f update readme 2015-09-18 09:01:03 -04:00
Erik 9a05f6043b tweaks to once 2015-09-17 23:52:23 -04:00
Erik Little 70c7dacde9 Merge pull request #183 from KevinMartin/patch-1
Adds SocketIOClient#once(event, callback)
2015-09-17 23:22:22 -04:00
Kevin Jose Martin a9b4193fe4 Fix "Variable 'handler' captured by a closure before being initialized" error 2015-09-17 22:06:12 -04:00
Kevin Jose Martin aaaf9dc451 Filter against SocketEventHandler#id 2015-09-17 21:49:18 -04:00
Kevin Jose Martin fe8469cfc6 Add SocketEventHandler#id to filter against 2015-09-17 21:48:09 -04:00
Kevin Jose Martin f5c3a2cac9 Add strict equality and execute "callback" as non-optional 2015-09-17 21:08:37 -04:00
Kevin Jose Martin 7d26bd3ee8 Fix type declarations 2015-09-17 21:00:56 -04:00
Kevin Jose Martin 136847fd77 Fix "Variable used within its own initial value" error 2015-09-17 20:41:34 -04:00
Kevin Jose Martin 9b3f84dcd0 Remove type declarations 2015-09-17 20:33:36 -04:00
Kevin Jose Martin a72f96759e Adds SocketIOClient#once(event, callback)
When the specified event is emitted, the handler deregisters itself.
2015-09-17 18:19:49 -04:00
Erik a81f925671 make note of https 2015-09-17 13:33:37 -04:00
Erik 4997294186 clean up readme 2015-09-17 09:47:02 -04:00
Erik ba5638a109 Revert "tweak to objective-c api"
This reverts commit d0a57ca353.
2015-09-17 09:09:02 -04:00
Erik 978bd2614e bump version 2015-09-17 09:08:58 -04:00
Erik 2f2bd49045 fix socketio/socket.io-client-swift#181 2015-09-17 09:06:09 -04:00
Erik f889d37e9b update readme. This api is probably going to change again 2015-09-16 12:49:25 -04:00
Erik 67afbcbd56 mess around with api 2015-09-16 12:46:19 -04:00
Erik d0a57ca353 tweak to objective-c api 2015-09-16 11:16:12 -04:00
Erik Little 9355fc5077 Update README.md 2015-09-15 18:27:50 -04:00
Erik fd21ca00d3 bump version 2015-09-14 15:44:43 -04:00
Erik f818d64405 fix socketio/socket.io-client-swift#177 2015-09-14 15:40:13 -04:00
Erik Little 55289d69a3 Update README.md 2015-09-14 13:16:33 -04:00
Erik 5dc0dfa9aa change travis icon to point to master 2015-09-14 13:15:20 -04:00
Erik 2e7be97a38 bump version 2015-09-14 13:12:19 -04:00
Erik 60e0142955 further tweaks to stringreader 2015-09-13 14:05:10 -04:00
Erik e84acb1471 only need to get the substring once 2015-09-13 13:56:51 -04:00
Erik 8044d6fc1c don't need to call predacessor 2015-09-13 13:46:36 -04:00
Erik e3ff1f434b add license 2015-09-13 13:39:51 -04:00
Erik ca67e9e47e use pure swift 2015-09-13 13:37:43 -04:00
Erik 108aa4b08a remove old debug print 2015-09-13 08:20:52 -04:00
Erik f5f2a15133 tweaks to string reading 2015-09-12 21:26:09 -04:00
Erik Little ec76704631 Merge pull request #175 from socketio/engine-polling-refactor
Refactor engine polling. Change SocketGenericParser to SocketStringRe…
2015-09-12 18:05:42 -04:00
Erik 2e9232365d remove unused property 2015-09-12 17:14:30 -04:00
Erik a91fc638f2 remove old log message 2015-09-12 17:12:12 -04:00
Erik e634b131fb Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into engine-polling-refactor
* 'swift-2' of https://github.com/socketio/socket.io-client-swift:
  replay xctool with xcodebuild
2015-09-12 17:08:05 -04:00
Erik 0e0d47b6ed Refactor engine polling. Change SocketGenericParser to SocketStringReader 2015-09-12 17:04:34 -04:00
Erik Little 4009e577b7 Merge pull request #174 from lightsprint09/fix-travis-xctool
replay xctool with xcodebuild
2015-09-12 13:11:04 -04:00
Lukas Schmidt bee997aff4 replay xctool with xcodebuild
xcodebuild doesn’t format tests as well as xctool but it works at the
moment.

Change back later
2015-09-12 19:04:27 +02:00
Erik Little f82aafd5c8 Merge pull request #172 from NachoSoto/apple-tv
Added support for tvOS
2015-09-11 21:51:03 -04:00
NachoSoto 07f9d4f548 Added support for tvOS
## Changes:

- Duplicated target for both framework and tests.
- Set the right platform on new targets.
- Changed `tvOS` framework target product name to `SocketIO`.
- Changed targets `plist`s to use the existing ones, and removed the copies.
- Configured scheme to use the right test target.
- Shared scheme.
- Verified `tvOS` tests pass.
2015-09-12 00:15:07 +00:00
Erik Little 17444dd4a3 Merge pull request #170 from NachoSoto/swift2-comments
Code improvements to Swift 2 branch
2015-09-11 18:46:54 -04:00
Lukas Schmidt 6a10f72443 Merge branch 'swift-2' 2015-09-11 10:22:47 +02:00
NachoSoto c6997f32dd Fixed indentation 2015-09-11 05:52:17 +00:00
NachoSoto e955699b21 SSLCert is now private 2015-09-11 05:43:16 +00:00
NachoSoto 2bb7360918 WebSockets: removed unnecessary weaks and simplified code 2015-09-11 05:42:55 +00:00
NachoSoto d5b9afd28d SwiftRegex does not need to be exposed 2015-09-11 05:39:24 +00:00
NachoSoto adb3650609 SwiftRegex: failing with fatalError 2015-09-11 05:38:08 +00:00
NachoSoto dc50af1505 SwiftRegex: changed static method to static to avoid unnecessary dynamic dispatching 2015-09-11 05:37:58 +00:00
NachoSoto bad0d4b419 SocketPacket: using Logger instead of print 2015-09-11 05:36:05 +00:00
NachoSoto b8cfdc8fd2 SocketIOClient: simplified conditional 2015-09-11 05:33:40 +00:00
NachoSoto a43548e203 SocketIOClient: remove unnecessary optional 2015-09-11 05:33:01 +00:00
NachoSoto 2bc72e1975 SocketIOClient: removed unnecessary weak self 2015-09-11 05:31:41 +00:00
NachoSoto 1739afa670 SocketIOClient: added assertion to check timeoutAfter is not negative 2015-09-11 05:28:28 +00:00
NachoSoto 40d76cdbeb SocketIOClient: making a few fields private 2015-09-11 05:26:56 +00:00
NachoSoto 4f2040fbfd Simplified SocketEngine.swift 2015-09-11 05:25:01 +00:00
Erik d2ae3705ff Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into swift-2
* 'swift-2' of https://github.com/socketio/socket.io-client-swift:
  Use swift 2 guard statement
  Fix use-after-release issue in WebSocket
2015-09-10 16:33:11 -04:00
Erik a634f5bacc simplify socketengine 2015-09-10 16:32:57 -04:00
Erik Little 259e543ad5 Merge pull request #167 from hankbao/swift-2-fix-use-after-release
Fix use-after-release issue in WebSocket
2015-09-09 11:44:05 -04:00
Hank Bao 713ce46e3b Use swift 2 guard statement 2015-09-09 22:40:09 +08:00
Hank Bao 44508a5193 Fix use-after-release issue in WebSocket 2015-09-09 22:33:35 +08:00
Erik 80cfe8c534 merge master 2015-09-08 09:58:38 -04:00
Erik 8320e296e9 bump version again 2015-09-08 09:30:33 -04:00
Erik 31a2079222 fix warning 2015-09-08 09:22:37 -04:00
Erik c9d26ebd65 bump version 2015-09-08 09:20:29 -04:00
Erik 77e1da2b51 fix socketio/socket.io-client-swift#166 2015-09-08 09:19:17 -04:00
Erik 8a911a871e Fix socketio/socket.io-client-swift#166 2015-09-08 09:10:37 -04:00
Erik d8c8b4941e fix case with nsdata in json 2015-09-08 09:00:57 -04:00
Erik 520a765c22 fix file location 2015-09-08 08:36:35 -04:00
Erik 5d9a8e88bf don't need to specifiy get 2015-09-07 17:56:53 -04:00
Erik ec200e78bb Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into swift-2
* 'swift-2' of https://github.com/socketio/socket.io-client-swift:
  use optionals instead of try/catch
  clean up code style
  disable locale test
  clean up using guard
  fix join namespace parse
  refactor, make use of try catch
  complete use of parser
  using parser for namespace
  use new parser for binary
  clean up code
  refactor clean up code
  socket parser Test
  SocketAckManagerTest
2015-09-07 16:53:14 -04:00
Erik 70b06a2248 small tweak 2015-09-07 16:53:10 -04:00
Erik Little 6cdacefdec Merge pull request #164 from lightsprint09/more-tests
More tests
2015-09-07 16:52:22 -04:00
Lukas Schmidt 222f622d3a use optionals instead of try/catch 2015-09-07 21:29:51 +02:00
Lukas Schmidt 91cc683b5b clean up code style 2015-09-07 20:25:13 +02:00
Lukas Schmidt 12f607e3c3 disable locale test 2015-09-07 19:34:45 +02:00
Lukas Schmidt 568b2ae1bc clean up using guard 2015-09-07 19:28:19 +02:00
Erik c8c67d66a8 typing dictionary might not always be right 2015-09-07 13:26:58 -04:00
Lukas Schmidt 70cacb025f fix join namespace parse 2015-09-07 19:19:22 +02:00
Erik 5fdea20455 simplify socketpacket methods 2015-09-07 13:15:54 -04:00
Lukas Schmidt 2bd612e47a refactor, make use of try catch 2015-09-07 15:08:10 +02:00
Lukas Schmidt fb9b19820b complete use of parser 2015-09-07 14:44:43 +02:00
Lukas Schmidt 8bae7d06d2 using parser for namespace 2015-09-07 13:53:43 +02:00
Lukas Schmidt 0b8be08a54 use new parser for binary 2015-09-07 12:53:28 +02:00
Lukas Schmidt 6f16694ed2 Merge remote-tracking branch 'origin/socketio/swift-2' into more-tests
Conflicts:
	SocketIOClientSwift/SocketParser.swift
2015-09-06 23:49:05 +02:00
Lukas Schmidt 13087ff1b7 clean up code 2015-09-06 23:45:52 +02:00
Erik 648d9d9df0 println doesn't exist anymore 2015-09-06 17:44:41 -04:00
Lukas Schmidt 16ed2bd130 refactor clean up code 2015-09-06 22:45:18 +02:00
Lukas Schmidt de0d0b8676 socket parser Test 2015-09-06 20:04:10 +02:00
Lukas Schmidt e79199d2e6 SocketAckManagerTest 2015-09-05 18:48:56 +02:00
Erik ac023013d4 change logging 2015-09-04 09:41:40 -04:00
Erik Little 0cfdd0b005 Merge pull request #161 from lightsprint09/logger
Logger +  Missing Test code
2015-09-04 09:27:55 -04:00
Lukas Schmidt f32c0850ac missing code 2015-09-04 14:51:08 +02:00
Lukas Schmidt fe7fb3ea4e improve status enum readability 2015-09-04 13:49:56 +02:00
Lukas Schmidt 4de0652568 improve logger api 2015-09-04 13:48:19 +02:00
Lukas Schmidt 6e43e58988 Merge remote-tracking branch 'socketio/swift-2' 2015-09-04 07:50:18 +02:00
Erik d6e1510cbf update websocket library 2015-09-03 23:32:48 -04:00
Erik 13440ce6b1 small tweak 2015-09-03 16:24:05 -04:00
Erik d81cbd7d24 fix unsafeBitCast error 2015-09-03 15:20:15 -04:00
Erik a147ebcd85 Default logging won't use another dispatch queue 2015-09-03 15:14:25 -04:00
Erik 8d0af14f04 add ability to specify custom logger 2015-09-03 15:10:18 -04:00
Erik 0ff4cb9713 remove old check 2015-09-03 12:27:24 -04:00
Erik Little 2ae994a031 Add travis build icon for swift-2 branch 2015-09-03 12:08:42 -04:00
Erik Little 0dc4f863f3 Merge pull request #158 from lightsprint09/fix-travis-ci-tests
Fix travis ci tests
2015-09-03 11:59:08 -04:00
Lukas Schmidt 0fb9be6247 clean debug code 2015-09-03 16:52:43 +02:00
Lukas Schmidt 69b3958796 single connection 2015-09-03 16:47:06 +02:00
Lukas Schmidt 110a6748ab cleanup 2015-09-03 14:06:09 +02:00
Lukas Schmidt e238293711 weak connection expection 2015-09-03 13:49:27 +02:00
Lukas Schmidt dfc905d9c3 refactor 2015-09-03 08:13:40 +02:00
Lukas Schmidt 530e6f8f9d Merge branch 'socketio/swift-2' 2015-09-03 07:57:37 +02:00
Lukas Schmidt 7bf1a40c54 Merge branch 'swift-2' 2015-09-03 07:55:08 +02:00
Erik e91f1031d6 Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into swift-2
* 'swift-2' of https://github.com/socketio/socket.io-client-swift:
  test
  use xcodebuild
  running tests
  next signing tests
  turn of code signing
  code signing
  correct scheme
  travis support
2015-09-02 12:03:19 -04:00
Erik adf8536c0c point to test server 2015-09-02 12:02:02 -04:00
Erik Little c1f80dc0c5 Merge pull request #156 from lightsprint09/travis-ci-test
Travis ci test
2015-09-02 11:01:46 -04:00
Lukas Schmidt 1777d490c5 test 2015-08-31 23:38:44 +02:00
Lukas Schmidt 5471411f74 use xcodebuild 2015-08-31 23:35:31 +02:00
Lukas Schmidt cd2ee8950f running tests 2015-08-31 22:56:52 +02:00
Lukas Schmidt 672e3601ed next signing tests 2015-08-31 22:39:16 +02:00
Lukas Schmidt f3ed05e970 turn of code signing 2015-08-31 22:32:01 +02:00
Lukas Schmidt e19a28684b code signing 2015-08-31 22:27:01 +02:00
Lukas Schmidt 39a7a4f337 correct scheme 2015-08-31 22:18:35 +02:00
Lukas Schmidt 3234b71b5b travis support 2015-08-31 21:07:25 +02:00
Lukas Schmidt 80d7622095 Merge branch 'socketio/swift-2' 2015-08-31 20:58:07 +02:00
Erik 8dc7121355 merge master 2015-08-31 09:34:14 -04:00
Erik 17426c1432 fix socketio/socket.io-client-swift#152 2015-08-31 09:22:56 -04:00
Erik 5a73a5e6da style 2015-08-28 13:42:04 -04:00
Erik 1f5402ce1c use computed variables 2015-08-27 09:45:27 -04:00
Erik Little 9510ef9d4f Merge pull request #151 from NachoSoto/swift-2
Using new Xcode 7 -Owholemodule optimization setting
2015-08-27 09:10:52 -04:00
NachoSoto 2a7ec38d48 Using new Xcode 7 -Owholemodule optimization setting 2015-08-27 04:21:06 +00:00
Erik ccd6dcbf0a update for latest beta 2015-08-25 09:31:33 -04:00
Erik 4fdb49ea2f use static variable for log 2015-08-18 10:19:58 -04:00
Erik 2351637ab4 don't need to unwrap 2015-08-18 10:07:57 -04:00
Erik 58097fa39e leave it up to the engineclient how to handle messages 2015-08-18 10:05:51 -04:00
Erik 4c9d6ef3de refactor socketpacket 2015-08-17 14:47:14 -04:00
Erik aa43107ad6 remove unused dispatch queue 2015-08-17 11:43:16 -04:00
Erik 46cea36df7 bump version 2015-08-17 00:15:39 -04:00
Erik 9c3d991bed fix bug in websocket library 2015-08-17 00:09:33 -04:00
Erik 6ee1daeaf7 fix bug in websocket library 2015-08-17 00:09:04 -04:00
Erik 09a26c0b1c remove all data on engine close 2015-08-17 00:04:13 -04:00
Erik f752507a11 style 2015-08-14 22:08:33 -04:00
Erik 2cafec6f12 move enum, better description 2015-08-14 16:20:43 -04:00
Erik 7ebcd7439f refactor, fix reconnect bug, fix internalmessages 2015-08-13 09:56:22 -04:00
Erik 5e92fc323d dammit 2015-08-11 10:05:35 -04:00
Erik c2b927fd02 oops 2015-08-11 10:04:43 -04:00
Erik 4014286da2 style 2015-08-11 10:03:35 -04:00
Erik 884b73c777 clean up 2015-08-11 09:54:59 -04:00
Erik b563334d14 clean up enums 2015-08-11 08:33:11 -04:00
Erik 848f7e5da7 clean up enums 2015-08-11 08:31:23 -04:00
Erik 0fd8a9540b don't remove engine 2015-08-10 11:00:22 -04:00
Erik 42aced5e9c don't remove engine 2015-08-10 11:00:01 -04:00
Erik Little b52684cb8f Merge pull request #141 from lightsprint09/API-improvements
Api improvements
2015-08-10 10:57:13 -04:00
Lukas Schmidt 25464ffb9d objc suppoert 2015-08-10 15:47:59 +02:00
Lukas Schmidt d0f091e983 remove unused variables 2015-08-10 07:44:01 +02:00
Lukas Schmidt 889ad404bc remove compiler warnings 2015-08-10 07:42:09 +02:00
Lukas Schmidt 6fa7636261 working test
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 07:14:52 +02:00
Lukas Schmidt 5eeac96b2b fix issues
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 07:04:11 +02:00
Lukas Schmidt f46629f850 Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into swift-2 2015-08-10 06:34:33 +02:00
Lukas Schmidt 84bb6b7dad update tests
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 06:33:32 +02:00
Lukas Schmidt 145448c087 Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into API-improvements 2015-08-10 06:22:27 +02:00
Lukas Schmidt 184b97ef8c fix merge issues
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 06:21:29 +02:00
Lukas Schmidt d0ec1de566 merge
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 06:18:37 +02:00
Lukas Schmidt 643ddb5bf9 Merge branch 'swift-2' of https://github.com/socketio/socket.io-client-swift into API-improvements
# Conflicts:
#	SocketIOClientSwift/SocketEngine.swift
#	SocketIOClientSwift/SocketIOClient.swift
#	SocketIOClientSwift/SocketTypes.swift

Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-10 06:18:28 +02:00
Erik 469caf1b54 update for latest beta 2015-08-06 14:12:35 -04:00
Erik c38412cae6 bump version 2015-08-05 12:27:46 -04:00
Erik 8bde261acb fix socketio/socket.io-client-swift#137 2015-08-05 12:25:37 -04:00
Erik 9b9becebae bump version 2015-08-05 06:14:44 -04:00
Lukas Schmidt 63a257ac80 Merge remote-tracking branch 'origin/socketio/swift-2' into API-improvements
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>

# Conflicts:
#	SocketIOClientSwift/SocketTypes.swift
2015-08-05 12:14:06 +02:00
Erik 514193e6ec Merge master 2015-08-05 06:12:35 -04:00
Lukas Schmidt 969e6d6ea8 minor imporvements
Signed-off-by: Lukas Schmidt <lukas.schmi@gmail.com>
2015-08-05 12:12:21 +02:00
Erik ffbe1e4ec4 add option for handle queue 2015-08-05 06:09:24 -04:00
Erik 80ea42c91f document objc method 2015-08-05 06:03:06 -04:00
Lukas Schmidt 0308e274cd Merge branch 'socketio/swift-2' into swift-2 2015-08-05 10:03:14 +02:00
Erik dd71d4954d update readme 2015-08-03 13:41:58 -04:00
Erik 06e2311acc fix socketio/socket.io-client-swift#133 can't expose variadics to objective-c 2015-08-03 12:41:14 -04:00
Erik 2579c04f67 better swift style 2015-08-03 10:07:59 -04:00
Erik Little 137fd1229b Merge pull request #127 from lightsprint09/tests
Tests for socket.io client
2015-08-02 17:19:24 -04:00
Lukas Schmidt 6650afd3e4 Merge branch 'socketio/swift-2' into tests 2015-08-02 20:05:43 +02:00
Erik 150e26aefd fix getting args for ack and binary-ack 2015-08-02 13:40:45 -04:00
Erik f0a45e13e2 clean up 2015-08-02 13:09:18 -04:00
Lukas Schmidt 7800591367 cleanup status api 2015-08-02 18:47:37 +02:00
Lukas Schmidt 92367fc796 minor improvements using let / guard 2015-08-02 18:23:48 +02:00
Lukas Schmidt fbe3bd9b30 Merge remote-tracking branch 'socketio/master' into swift-2 2015-08-02 17:50:34 +02:00
Lukas Schmidt e25afd60fd Merge branch 'socketio/swift-2' into tests 2015-08-02 17:50:15 +02:00
Lukas Schmidt f0b4f077d4 fix crash 2015-08-02 17:44:06 +02:00
Lukas Schmidt 1b08411ed4 refactored iOS testcases
Add test cases for complex data structure (JSON, multiple data emit)
without binary Buffer attached
2015-08-02 17:29:16 +02:00
Lukas Schmidt bf3e28df81 improve tests on server 2015-08-02 17:28:09 +02:00
Lukas Schmidt 4086ce7d75 relocate test cases for better understanding 2015-08-02 15:07:05 +02:00
Erik feea80a2f9 use immutable values 2015-07-31 16:05:33 -04:00
Lukas Schmidt a0e3052893 test server 2015-07-28 17:02:44 +02:00
Lukas Schmidt 79848b1ce0 cleanup 2015-07-28 16:15:12 +02:00
Lukas Schmidt 30cf2bb67a namespace tests 2015-07-28 14:46:30 +02:00
Lukas Schmidt b1b9a7edaf more tests 2015-07-28 14:25:15 +02:00
Erik cf98f09b93 Merge branch 'master' into swift-2
* master:
  change to default session config
2015-07-27 18:50:26 -04:00
Erik e792006245 change to default session config 2015-07-27 18:50:12 -04:00
Erik 3c9c473e70 clean up socketpacket 2015-07-27 17:12:57 -04:00
Lukas Schmidt 252181b0c5 clean up 2015-07-27 11:33:41 +02:00
Lukas Schmidt a4988e6404 namespace tests 2015-07-26 17:14:21 +02:00
Lukas Schmidt a1af98e173 refactor 2015-07-26 16:58:08 +02:00
Lukas Schmidt aa6db7c837 remove old files 2015-07-26 12:42:18 +02:00
Lukas Schmidt a07916fb2f basic emit tests 2015-07-25 18:45:41 +02:00
Lukas Schmidt 4b9db85a49 update api 2015-07-24 20:11:47 +02:00
Lukas Schmidt 149e6137af Merge branch 'socketio/swift-2' into tests 2015-07-24 19:56:21 +02:00
Lukas Schmidt 224c660e4c basic test structure / tests 2015-07-24 19:55:35 +02:00
Erik 7b795fd989 Merge branch 'master' into swift-2
* master:
  bump version
2015-07-24 08:02:26 -04:00
Erik 67f57daaab bump version 2015-07-24 08:00:31 -04:00
Erik 846f10eb13 Merge branch 'master' into swift-2
* master:
  update readme
  change api for emitack callback
2015-07-23 13:51:50 -04:00
Erik 11730b5fcd update readme 2015-07-22 19:10:55 -04:00
Erik 47a839b934 change api for emitack callback 2015-07-22 19:09:47 -04:00
Erik 94a3844181 warnings 2015-07-22 08:49:51 -04:00
Erik 01aa6354e3 merge master 2015-07-22 07:45:40 -04:00
Erik ac663a8875 bump websocket version 2015-07-22 06:28:06 -04:00
Erik a277e88c3b update for xcode 7 beta 4 2015-07-21 16:19:15 -04:00
Erik fba226a6de bump version 2015-07-14 11:42:59 -04:00
Erik d073fa8a83 Merge branch 'master' into swift-2
* master:
  maybe fix socketio/socket.io-client-swift#100 and socketio/socket.io-client-swift#22
  Added SocketIOClient.removeAllHandlers
  Updated BuildableName in schemes
  bump version
2015-07-12 21:11:18 -04:00
Erik 8928ce2693 maybe fix socketio/socket.io-client-swift#100 and socketio/socket.io-client-swift#22 2015-07-12 20:40:41 -04:00
Erik 5057226a6c maybe fix socketio/socket.io-client-swift#100 and socketio/socket.io-client-swift#22 2015-07-12 20:40:23 -04:00
Erik Little ebe9384604 Merge pull request #118 from NachoSoto/remove-handlers
Remove handlers
2015-07-12 20:39:31 -04:00
NachoSoto 5f75e6080b Added SocketIOClient.removeAllHandlers 2015-07-13 00:09:05 +00:00
NachoSoto c40b7c169f Updated BuildableName in schemes 2015-07-13 00:08:56 +00:00
Erik ea0fc9933e bump version 2015-07-12 16:26:02 -04:00
Erik c21799abac merge master 2015-07-12 09:56:48 -04:00
Erik Little 43827914b7 Merge pull request #117 from NachoSoto/master
Added project with iOS and Mac targets => Carthage support
2015-07-12 09:49:40 -04:00
NachoSoto 22b9a1e2f2 Added Carthage instructions to README 2015-07-12 01:06:26 +00:00
NachoSoto fd66a9fa62 Created project with iOS and Mac targets 2015-07-12 00:58:09 +00:00
Erik 68078e50d5 the weirdness with objc blocks is fixed in Swift 2 2015-07-10 06:45:58 -04:00
Erik 8daa7da426 clean up namespace logic 2015-07-09 12:29:26 -04:00
Erik 24583f19c1 fix socketio/socket.io-client-swift#113 2015-07-09 10:44:57 -04:00
Erik 652c81a80e add back default value 2015-07-09 10:38:24 -04:00
Erik 422b93f577 Merge branch 'master' into swift-2
* master:
  Invalidate timer on reconnect failure
  fix socketio/socket.io-client-swift#110 calling close while trying to reconnect
2015-07-03 14:07:03 -04:00
Erik 998089df91 Invalidate timer on reconnect failure 2015-07-03 13:58:06 -04:00
Erik 283644b75c fix socketio/socket.io-client-swift#110 calling close while trying to reconnect 2015-07-03 13:53:40 -04:00
Erik 38a7cc8648 whitespace 2015-07-03 09:04:40 -04:00
Erik a22869efad Just use regular array for packets 2015-07-03 09:03:44 -04:00
Erik 6ecd1e2a79 merge master 2015-07-01 07:10:19 -04:00
Erik 846897157c bump version 2015-07-01 07:07:32 -04:00
Erik a49f8f19cf add extraHeaders option fixes. nuclearace/Socket.IO-Client-Swift#64 2015-07-01 07:05:06 -04:00
Erik b388df798b shorter expression in off 2015-06-29 21:25:00 -04:00
Erik 531a9784da make it clear as to what language 2015-06-29 18:13:45 -04:00
Erik c34a660cae update readme 2015-06-29 18:12:46 -04:00
Erik 9484bc9614 update readme 2015-06-29 18:11:33 -04:00
Erik 7206fa6d5c change readme 2015-06-26 09:57:37 -04:00
Erik 362f4e90b8 merge master 2015-06-24 07:05:38 -04:00
Erik d8f65c2804 bump version 2015-06-24 06:52:24 -04:00
Erik ca3f3e810d fix socketio/socket.io-client-swift#97 2015-06-24 06:51:47 -04:00
Erik 77eb1603ac Merge branch 'master' into swift-2
* master:
  bump version
2015-06-23 22:01:19 -04:00
Erik 63021eb995 bump version 2015-06-23 21:52:05 -04:00
Erik eb00be0aaa Merge branch 'master' into swift-2
* master:
  set connecting
2015-06-23 18:57:49 -04:00
Erik d8e3408565 set connecting 2015-06-23 18:57:37 -04:00
Erik 9454a47ef4 fix binary 2015-06-23 15:11:30 -04:00
Erik bd88ff763b change default type 2015-06-19 09:28:13 -04:00
Erik f41b64137e Merge branch 'master' into swift-2
* master:
  use computed variable for sid
2015-06-19 09:24:15 -04:00
Erik df2f149f85 handle acks better 2015-06-19 08:12:27 -04:00
Erik f2ef3344c0 update ignorefile 2015-06-19 08:03:55 -04:00
Erik 65be52418d remove old stuff 2015-06-19 08:02:51 -04:00
Erik 76637d160e use struct for socketpacket 2015-06-19 08:00:09 -04:00
Erik f17575b35c use computed variable for sid 2015-06-16 05:14:32 -04:00
Erik f2e5a1437b use computed variable for sid 2015-06-16 05:13:08 -04:00
Erik a0c676bc54 unify objc/swift constructors 2015-06-12 09:42:44 -04:00
Erik 5854262280 Fix reference error 2015-06-12 09:39:39 -04:00
Erik 1c8fcee772 remove comment 2015-06-12 09:23:11 -04:00
Erik 11d8430537 use struct 2015-06-11 11:50:30 -04:00
Erik a15b57e900 extract methods, clean up 2015-06-10 19:27:07 -04:00
Erik fafeebe185 remove warnings 2015-06-08 21:03:49 -04:00
Erik 66622fffb3 I hope Swift fixes the case where I use variadics, because this ugly 2015-06-08 20:24:57 -04:00
Erik 7bf35e182c tweaks 2015-06-08 20:23:22 -04:00
Erik 78727dc0ee untested with socket.io, this just compiles 2015-06-08 20:02:59 -04:00
Erik 58571e5387 bump version 2015-06-07 13:15:03 -04:00
Erik 1a54decd51 fix socketio/socket.io-client-swift#93 2015-06-06 22:30:56 -04:00
Erik d982cdc1b2 only do interpolation when logging 2015-06-06 13:15:22 -04:00
Erik 079063e396 bump version 2015-06-05 06:59:20 -04:00
Erik 33d5fd3f10 fix base64 data 2015-06-05 06:57:59 -04:00
Erik 3be5621263 remove comment 2015-05-31 11:09:25 -04:00
Erik 81ab71f519 extract methods 2015-05-31 11:07:48 -04:00
Erik bfeec57c04 don't need type 2015-05-29 10:30:59 -04:00
Erik 0b09a1357c use didset instead of computed variable 2015-05-29 10:29:26 -04:00
Erik e8dfe589ac redo pingtimeouts 2015-05-29 10:10:24 -04:00
Erik fcebc870c3 fix socket.io/socket.io-client-swift#87 2015-05-27 07:28:06 -04:00
Erik eeadccec94 bump version 2015-05-24 08:11:30 -04:00
Erik fa0d5022cf fix socketio/socket.io-client-swift#85 2015-05-24 08:10:43 -04:00
Erik 2fdd1313a8 move open logic to method 2015-05-22 07:26:52 -04:00
Erik 61b4628d3e only use self when needed 2015-05-19 22:13:08 -04:00
Erik 77ed87d0d4 remove dumb comment 2015-05-18 18:43:26 -04:00
Erik a6f68e7b70 tweaks 2015-05-17 08:28:10 -04:00
Erik 2453f33191 bump version 2015-05-14 13:22:54 -04:00
Erik bb3d7fbded add leavenamepsace method, expose joinNamespace 2015-05-14 13:22:25 -04:00
Erik f54153f3d4 fix objc example 2015-05-13 13:40:33 -04:00
Erik 709ecc30b3 tweak ack message 2015-05-13 08:36:08 -04:00
Erik 72dd2ef364 use same example for objc 2015-05-13 08:35:19 -04:00
Erik 9ec521a6de bump version. Changes to connect 2015-05-11 12:40:05 -04:00
Erik 69c67a2b81 Merge branch 'master' into redoconnects 2015-05-11 09:21:03 -04:00
Erik dd068cb480 clarify what nsp does 2015-05-11 09:20:47 -04:00
Erik 3abb26565b tweak closing engine 2015-05-11 09:19:46 -04:00
Erik d7d1da704f document connect method 2015-05-09 15:30:39 -04:00
Erik 5a5dc70203 fix nuclearace/Socket.IO-Client-Swift#46 2015-05-09 15:20:03 -04:00
Erik c049f62028 bump version 2015-05-07 10:34:29 -04:00
Erik 88c139ed0c clean up 2015-05-07 10:32:30 -04:00
Erik fdfd4dbc4d newlines 2015-05-01 11:37:59 -04:00
Erik 9e0726d61f fix socketio/socket.io-client-swift#72 2015-04-29 23:34:49 -04:00
Erik 2ee104bb5e bump version 2015-04-29 10:07:51 -04:00
Erik 90bbc9521f work on socketio/socket.io-client-swift#70 2015-04-29 00:39:53 -04:00
Erik 7a1a0d91f9 work on socketio/socket.io-client-swift#70 2015-04-29 00:29:36 -04:00
60 changed files with 6988 additions and 2856 deletions

No files matched your search

+23
View File
@@ -1,6 +1,9 @@
.DS_Store
.AppleDouble
.LSOverride
*.xcodeproj
.build/*
Packages/*
# Icon must end with two \r
Icon
@@ -23,3 +26,23 @@ Icon
Network Trash Folder
Temporary Items
.apdisk
# Xcode
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
Socket.IO-Test-Server/node_modules/*
+1
View File
@@ -0,0 +1 @@
3.0
+13
View File
@@ -0,0 +1,13 @@
language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode8
branches:
only:
- master
- development
before_install:
- 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
+5
View File
@@ -0,0 +1,5 @@
import PackageDescription
let package = Package(
name: "SocketIO"
)
+125 -43
View File
@@ -1,38 +1,48 @@
[![Build Status](https://travis-ci.org/socketio/socket.io-client-swift.svg?branch=master)](https://travis-ci.org/socketio/socket.io-client-swift)
#Socket.IO-Client-Swift
Socket.IO-client for iOS/OS X.
##Example
```swift
let socket = SocketIOClient(socketURL: "localhost:8080")
import SocketIO
let socket = SocketIOClient(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .forcePolling(true)])
socket.on("connect") {data, ack in
println("socket connected")
print("socket connected")
}
socket.on("currentAmount") {data, ack in
if let cur = data?[0] as? Double {
socket.emitWithAck("canUpdate", cur)(timeout: 0) {data in
if let cur = data[0] as? Double {
socket.emitWithAck("canUpdate", cur)(0) {data in
socket.emit("update", ["amount": cur + 2.50])
}
ack?("Got your currentAmount", "dude")
ack.with("Got your currentAmount", "dude")
}
}
// Connect
socket.connect()
```
##Objective-C Example
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
@import SocketIO;
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:8080"];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
NSLog(@"connected");
[socket emit:@"echo" withItems:@[@"echo test"]];
[socket emitWithAck:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
NSLog(@"Got ack");
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
NSLog(@"socket connected");
}];
[socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
double cur = [[data objectAtIndex:0] floatValue];
[socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
[socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
});
[ack with:@[@"Got your currentAmount, ", @"dude"]];
}];
[socket connect];
@@ -47,24 +57,58 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
- Can be used from Objective-C
##Installation
Requires Swift 1.2/Xcode 6.3
Requires Swift 3/Xcode 8.x
If you need swift 2.3 use the swift2.3 branch (Pre-Swift 3 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 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)
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
Manually (iOS 7+)
-----------------
1. Copy the SocketIOClientSwift folder into your Xcode project. (Make sure you add the files to your target(s))
1. Copy the Source folder into your Xcode project. (Make sure you add the files to your target(s))
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
CocoaPods 0.36.0 or later (iOS 8+)
Swift Package Manager
---------------------
Add the project as a dependency to your Package.swift:
```swift
import PackageDescription
let package = Package(
name: "YourSocketIOProject",
dependencies: [
.Package(url: "https://github.com/socketio/socket.io-client-swift", majorVersion: 8)
]
)
```
Then import `import SocketIO`.
Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 8.0.2 # Or latest version
```
Run `carthage update --platform ios,macosx`.
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', '~> 1.3.2' # Or latest version
target 'YourApp' do
pod 'Socket.IO-Client-Swift', '~> 8.0.2' # Or latest version
end
```
Install pods:
@@ -73,44 +117,82 @@ Install pods:
$ pod install
```
Import in your swift file:
Import the module:
Swift:
```swift
import Socket_IO_Client_Swift
import SocketIO
```
Objective-C:
```Objective-C
@import SocketIO;
```
CocoaSeeds
-----------------
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v8.0.2", :files => "Source/*.swift" # Or latest version
```
Run `seed install`.
##API
Constructors
-----------
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values)
`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: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
`convenience init(socketURL: NSURL, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
Options
-------
- `reconnects: Bool` Default is `true`
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
- `reconnectWait: Int` Default is `10`
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
- `nsp: String` Default is `"/"`
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
- `log: Bool` If `true` socket will log debug messages. Default is false.
- `sessionDelegate: NSURLSessionDelegate` Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
- `path: String` - If the server uses a custom path. ex: `"/swift"`. Default is `""`
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. 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(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - 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.
2. `onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
3. `emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
4. `emit(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout: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.
6. `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.
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
10. `reconnect()` - Causes the client to reconnect to the server.
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.
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.
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
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.
Client Events
------
+6 -4
View File
@@ -1,19 +1,21 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "2.2.1"
s.module_name = "SocketIO"
s.version = "8.0.2"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
Supports ws/wss/polling connections and binary.
For socket.io 1.0+ and Swift 1.2.
For socket.io 1.0+ and Swift.
DESC
s.homepage = "https://github.com/socketio/socket.io-client-swift"
s.license = { :type => 'MIT' }
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.2.1' }
s.source_files = "SocketIOClientSwift/**/*.swift"
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v8.0.2' }
s.source_files = "Source/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:Socket.IO-Client-Swift.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2411B51F18A00EEBB58"
BuildableName = "SocketIO-MacTests.xctest"
BlueprintName = "SocketIO-MacTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2411B51F18A00EEBB58"
BuildableName = "SocketIO-MacTests.xctest"
BlueprintName = "SocketIO-MacTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2231B51F16C00EEBB58"
BuildableName = "SocketIO-iOSTests.xctest"
BlueprintName = "SocketIO-iOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2231B51F16C00EEBB58"
BuildableName = "SocketIO-iOSTests.xctest"
BlueprintName = "SocketIO-iOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
BuildableName = "SocketIO-tvOSTests.xctest"
BlueprintName = "SocketIO-tvOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
BuildableName = "SocketIO-tvOSTests.xctest"
BlueprintName = "SocketIO-tvOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+95
View File
@@ -0,0 +1,95 @@
var assert = require("assert")
module.exports = {
basicTest: {
assert: function(inputData) {
},
returnData: []
},
testNull: {
assert: function(inputData) {
assert(!inputData)
},
returnData: [null]
},
testBinary: {
assert: function(inputData) {
assert.equal(inputData.toString(), "gakgakgak2")
},
returnData: [new Buffer("gakgakgak2", "utf-8")]
},
testArray: {
assert: function(inputData) {
assert.equal(inputData.length, 2)
assert.equal(inputData[0], "test1")
assert.equal(inputData[1], "test2")
},
returnData: [["test3", "test4"]]
},
testString: {
assert: function(inputData) {
assert.equal(inputData, "marco")
},
returnData: ["polo"]
},
testBool: {
assert: function(inputData) {
assert(!inputData)
},
returnData: [true]
},
testInteger: {
assert: function(inputData) {
assert.equal(inputData, 10)
},
returnData: [20]
},
testDouble: {
assert: function(inputData) {
assert.equal(inputData, 1.1)
},
returnData: [1.2]
},
testJSON: {
assert: function(inputData) {
assert.equal(inputData.name, "test")
assert.equal(inputData.nestedTest.test, "test")
assert.equal(inputData.testArray.length, 1)
},
returnData: [{testString: "test", testNumber: 15, nestedTest: {test: "test"}, testArray: [1, 1]}]
},
testJSONWithBuffer: {
assert: function(inputData) {
assert.equal(inputData.name, "test")
assert.equal(inputData.nestedTest.test, "test")
assert.equal(inputData.testArray.length, 1)
},
returnData: [{testString: "test", testNumber: 15, nestedTest: {test: "test"}, testArray: [new Buffer("gakgakgak2", "utf-8"), 1]}]
},testUnicode: {
assert: function(inputData) {
assert.equal(inputData, "🚀")
},
returnData: ["🚄"]
},testMultipleItems: {
assert: function(array, object, number, string, bool) {
assert.equal(array.length, 2)
assert.equal(array[0], "test1")
assert.equal(array[1], "test2")
assert.equal(number, 15)
assert.equal(string, "marco")
assert.equal(bool, false)
},
returnData: [[1, 2], {test: "bob"}, 25, "polo", false]
},testMultipleItemsWithBuffer: {
assert: function(array, object, number, string, binary) {
assert.equal(array.length, 2)
assert.equal(array[0], "test1")
assert.equal(array[1], "test2")
assert.equal(number, 15)
assert.equal(string, "marco")
assert.equal(binary.toString(), "gakgakgak2")
},
returnData: [[1, 2], {test: "bob"}, 25, "polo", new Buffer("gakgakgak2")]
}
}
@@ -0,0 +1,10 @@
function socketCallback(testKey, socket, testCase) {
return function() {
testCase.assert.apply(undefined , arguments)
var emitArguments = testCase.returnData;
var ack = arguments[arguments.length - 1]
ack.apply(socket, emitArguments)
}
}
module.exports.socketCallback = socketCallback
+20
View File
@@ -0,0 +1,20 @@
function socketCallback(testKey, socket, testCase) {
return function() {
testCase.assert.apply(undefined , arguments)
var emitArguments = addArrays([testKey + "EmitReturn"], testCase.returnData)
socket.emit.apply(socket, emitArguments)
}
}
function addArrays(firstArray, secondArray) {
var length = secondArray.length
var i;
for(i = 0; i < length; i++) {
firstArray.push(secondArray[i])
}
return firstArray;
}
module.exports.socketCallback = socketCallback
+15
View File
@@ -0,0 +1,15 @@
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(6979)
var acknowledgementsEvents = require("./acknowledgementEvents.js")
var emitEvents = require("./emitEvents.js")
var socketEventRegister = require("./socketEventRegister.js")
socketEventRegister.register(io, emitEvents.socketCallback, "Emit")
socketEventRegister.register(io, acknowledgementsEvents.socketCallback, "Acknowledgement")
var nsp = io.of("/swift")
socketEventRegister.register(nsp, emitEvents.socketCallback, "Emit")
socketEventRegister.register(nsp, acknowledgementsEvents.socketCallback, "Acknowledgement")
+14
View File
@@ -0,0 +1,14 @@
{
"name": "socket.io-client-swift-test-server",
"version": "0.0.1",
"description": "A simple server to test aginst",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Lukas Schmidt",
"license": "MIT",
"dependencies": {
"socket.io": "^1.3.6"
}
}
@@ -0,0 +1,13 @@
var testCases = require("./TestCases.js")
function registerSocketForEvents(ioSocket, socketCallback, testKind) {
ioSocket.on('connection', function(socket) {
var testCase;
for(testKey in testCases) {
testCase = testCases[testKey]
socket.on((testKey + testKind), socketCallback(testKey, socket, testCase))
}
})
}
module.exports.register = registerSocketForEvents
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
+19
View File
@@ -0,0 +1,19 @@
//
// SocketIO-Mac.h
// SocketIO-Mac
//
// Created by Nacho Soto on 7/11/15.
//
//
#import <Cocoa/Cocoa.h>
//! Project version number for SocketIO-Mac.
FOUNDATION_EXPORT double SocketIO_MacVersionNumber;
//! Project version string for SocketIO-Mac.
FOUNDATION_EXPORT const unsigned char SocketIO_MacVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SocketIO_Mac/PublicHeader.h>
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,26 @@
//
// SocketAckManagerTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 04.09.15.
//
//
import XCTest
@testable import SocketIO
class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager()
func testAddAcks() {
let callbackExpection = self.expectation(description: "callbackExpection")
let itemsArray = ["Hi", "ho"]
func callback(_ items: [Any]) {
callbackExpection.fulfill()
}
ackManager.addAck(1, callback: callback)
ackManager.executeAck(1, with: itemsArray, onQueue: DispatchQueue.main)
waitForExpectations(timeout: 3.0, handler: nil)
}
}
@@ -0,0 +1,166 @@
//
// SocketBasicPacketTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/7/15.
//
//
import XCTest
@testable import SocketIO
class SocketBasicPacketTest: XCTestCase {
let data = "test".data(using: String.Encoding.utf8)!
let data2 = "test2".data(using: String.Encoding.utf8)!
func testEmpyEmit() {
let expectedSendString = "2[\"test\"]"
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testNullEmit() {
let expectedSendString = "2[\"test\",null]"
let sendData: [Any] = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmit() {
let expectedSendString = "2[\"test\",\"foo bar\"]"
let sendData = ["test", "foo bar"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmitWithQuotes() {
let expectedSendString = "2[\"test\",\"\\\"he\\\"llo world\\\"\"]"
let sendData = ["test", "\"he\"llo world\""]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2[\"test\",{\"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)
}
func testArrayEmit() {
let expectedSendString = "2[\"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\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data])
}
func testMultipleBinaryEmit() {
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, [data2, data])
}
func testEmitWithAck() {
let expectedSendString = "20[\"test\"]"
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString,
expectedSendString)
}
func testEmitDataWithAck() {
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)
XCTAssertEqual(packet.binary, [data])
}
// Acks
func testEmptyAck() {
let expectedSendString = "30[]"
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testNullAck() {
let expectedSendString = "30[null]"
let sendData = [NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringAck() {
let expectedSendString = "30[\"test\"]"
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONAck() {
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)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryAck() {
let expectedSendString = "61-0[{\"_placeholder\":true,\"num\":0}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data])
}
func testMultipleBinaryAck() {
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)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data2, data])
}
func testBinaryStringPlaceholderInMessage() {
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) {
var packet = packet
XCTAssertEqual(packet.event, "test")
_ = packet.addData(data)
_ = packet.addData(data2)
XCTAssertEqual(packet.args[0] as? String, "~~0")
} else {
XCTFail()
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//
// SocketEngineTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/15/15.
//
//
import XCTest
@testable import SocketIO
class SocketEngineTest: XCTestCase {
var client: SocketIOClient!
var engine: SocketEngine!
override func setUp() {
super.setUp()
client = SocketIOClient(socketURL: URL(string: "http://localhost")!)
engine = SocketEngine(client: client, url: URL(string: "http://localhost")!, options: nil)
client.setTestable()
}
func testBasicPollingMessage() {
let expect = expectation(description: "Basic polling test")
client.on("blankTest") {data, ack in
expect.fulfill()
}
engine.parsePollingMessage("15:42[\"blankTest\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testTwoPacketsInOnePollTest() {
let finalExpectation = expectation(description: "Final packet in poll test")
var gotBlank = false
client.on("blankTest") {data, ack in
gotBlank = true
}
client.on("stringTest") {data, ack in
if let str = data[0] as? String, gotBlank {
if str == "hello" {
finalExpectation.fulfill()
}
}
}
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDoesErrorOnUnknownTransport() {
let finalExpectation = expectation(description: "Unknown Transport")
client.on("error") {data, ack in
if let error = data[0] as? String, error == "Unknown transport" {
finalExpectation.fulfill()
}
}
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDoesErrorOnUnknownMessage() {
let finalExpectation = expectation(description: "Engine Errors")
client.on("error") {data, ack in
finalExpectation.fulfill()
}
engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectations(timeout: 3, handler: nil)
}
func testEngineDecodesUTF8Properly() {
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")
expect.fulfill()
}
engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlīne \\rtwo\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testEncodeURLProperly() {
engine.connectParams = [
"created": "2016-05-04T18:31:15+0200"
]
XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&created=2016-05-04T18%3A31%3A15%2B0200")
XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&created=2016-05-04T18%3A31%3A15%2B0200")
engine.connectParams = [
"forbidden": "!*'();:@&=+$,/?%#[]\" {}"
]
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()
}
}
}
@@ -0,0 +1,141 @@
//
// SocketNamespacePacketTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/11/15.
//
//
import XCTest
@testable import SocketIO
class SocketNamespacePacketTest: XCTestCase {
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: [Any] = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testNullEmit() {
let expectedSendString = "2/swift,[\"test\",null]"
let sendData: [Any] = ["test", NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringEmit() {
let expectedSendString = "2/swift,[\"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\",{\"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\"},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\",{\"_placeholder\":true,\"num\":0}]"
let sendData: [Any] = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data])
}
func testMultipleBinaryEmit() {
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, [data2, data])
}
func testEmitWithAck() {
let expectedSendString = "2/swift,0[\"test\"]"
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testEmitDataWithAck() {
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)
XCTAssertEqual(packet.binary, [data])
}
// Acks
func testEmptyAck() {
let expectedSendString = "3/swift,0[]"
let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/swift", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testNullAck() {
let expectedSendString = "3/swift,0[null]"
let sendData = [NSNull()]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testStringAck() {
let expectedSendString = "3/swift,0[\"test\"]"
let sendData = ["test"]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONAck() {
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)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryAck() {
let expectedSendString = "61-/swift,0[{\"_placeholder\":true,\"num\":0}]"
let sendData = [data]
let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/swift", ack: true)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data])
}
func testMultipleBinaryAck() {
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)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data2, data])
}
}
+53
View File
@@ -0,0 +1,53 @@
//
// SocketObjectiveCTest.m
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/25/16.
//
// Merely tests whether the Objective-C api breaks
//
#import <XCTest/XCTest.h>
@import SocketIO;
@interface SocketObjectiveCTest : XCTestCase
@property SocketIOClient* socket;
@end
@implementation SocketObjectiveCTest
- (void)setUp {
[super setUp];
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost"];
self.socket = [[SocketIOClient alloc] initWithSocketURL:url config:nil];
}
- (void)testOnSyntax {
[self.socket on:@"someCallback" callback:^(NSArray* data, SocketAckEmitter* ack) {
[ack with:@[@1]];
}];
}
- (void)testEmitSyntax {
[self.socket emit:@"testEmit" with:@[@YES]];
}
- (void)testEmitWithAckSyntax {
[self.socket emitWithAck:@"testAckEmit" with:@[@YES]](0, ^(NSArray* data) {
});
}
- (void)testOffSyntax {
[self.socket off:@"test"];
}
- (void)testSocketManager {
SocketClientManager* manager = [SocketClientManager sharedManager];
[manager addSocket:self.socket labeledAs:@"test"];
[manager removeSocketWithLabel:@"test"];
}
@end
+149
View File
@@ -0,0 +1,149 @@
//
// SocketParserTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 05.09.15.
//
//
import XCTest
@testable import SocketIO
class SocketParserTest: XCTestCase {
let testSocket = SocketIOClient(socketURL: URL(string: "http://localhost/")!)
//Format key: message; namespace-data-binary-id
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"] 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] 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),
"4[1, \"hello\"]": ("/", [1, "hello"], [], -1)]
func testDisconnect() {
let message = "1"
validateParseResult(message)
}
func testConnect() {
let message = "0"
validateParseResult(message)
}
func testDisconnectNameSpace() {
let message = "1/swift"
validateParseResult(message)
}
func testConnecttNameSpace() {
let message = "0/swift"
validateParseResult(message)
}
func testIdEvent() {
let message = "25[\"test\"]"
validateParseResult(message)
}
func testBinaryPlaceholderAsString() {
let message = "2[\"test\",\"~~0\"]"
validateParseResult(message)
}
func testNameSpaceArrayParse() {
let message = "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]"
validateParseResult(message)
}
func testNameSpaceArrayAckParse() {
let message = "3/swift,0[[\"test3\",\"test4\"]]"
validateParseResult(message)
}
func testNameSpaceBinaryEventParse() {
let message = "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
validateParseResult(message)
}
func testNameSpaceBinaryAckParse() {
let message = "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
validateParseResult(message)
}
func testNamespaceErrorParse() {
let message = "4/swift,"
validateParseResult(message)
}
func testErrorTypeString() {
let message = "4\"ERROR\""
validateParseResult(message)
}
func testErrorTypeDictionary() {
let message = "4{\"test\":2}"
validateParseResult(message)
}
func testErrorTypeInt() {
let message = "41"
validateParseResult(message)
}
func testErrorTypeArray() {
let message = "4[1, \"hello\"]"
validateParseResult(message)
}
func testInvalidInput() {
let message = "8"
switch testSocket.parseString(message) {
case .left(_):
return
case .right(_):
XCTFail("Created packet when shouldn't have")
}
}
func testGenericParser() {
var parser = SocketStringReader(message: "61-/swift,")
XCTAssertEqual(parser.read(count: 1), "6")
XCTAssertEqual(parser.currentCharacter, "1")
XCTAssertEqual(parser.readUntilOccurence(of: "-"), "1")
XCTAssertEqual(parser.currentCharacter, "/")
}
func validateParseResult(_ message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = testSocket.parseString(message)
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).isEqual(to: validValues.1), "\(packet.data)")
XCTAssertTrue((packet.binary as NSArray).isEqual(to: validValues.2), "\(packet.binary)")
XCTAssertEqual(packet.id, validValues.3)
} else {
XCTFail()
}
}
func testParsePerformance() {
let keys = Array(SocketParserTest.packetTypes.keys)
measure {
for item in keys.enumerated() {
_ = self.testSocket.parseString(item.element)
}
}
}
}
@@ -0,0 +1,168 @@
//
// SocketSideEffectTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/11/15.
//
//
import XCTest
@testable import SocketIO
class SocketSideEffectTest: XCTestCase {
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: URL(string: "http://localhost/")!)
socket.setTestable()
}
func testInitialCurrentAck() {
XCTAssertEqual(socket.currentAck, -1)
}
func testFirstAck() {
socket.emitWithAck("test")(0) {data in}
XCTAssertEqual(socket.currentAck, 0)
}
func testSecondAck() {
socket.emitWithAck("test")(0) {data in}
socket.emitWithAck("test")(0) {data in}
XCTAssertEqual(socket.currentAck, 1)
}
func testHandleAck() {
let expect = expectation(description: "handled ack")
socket.emitWithAck("test")(0) {data in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
}
socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleAck2() {
let expect = expectation(description: "handled ack2")
socket.emitWithAck("test")(0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expect.fulfill()
}
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(Data())
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleEvent() {
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleStringEventWithQuotes() {
let expect = expectation(description: "handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "\"hello world\"")
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"\\\"hello world\\\"\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleOnceEvent() {
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)
expect.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectations(timeout: 3, handler: nil)
}
func testOffWithEvent() {
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 1)
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 2)
socket.off("test")
XCTAssertEqual(socket.testHandlers.count, 0)
}
func testOffWithId() {
let handler = socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 1)
socket.on("test") {data, ack in }
XCTAssertEqual(socket.testHandlers.count, 2)
socket.off(id: handler)
XCTAssertEqual(socket.testHandlers.count, 1)
}
func testHandlesErrorPacket() {
let expect = expectation(description: "Handled error")
socket.on("error") {data, ack in
if let error = data[0] as? String, error == "test error" {
expect.fulfill()
}
}
socket.parseSocketMessage("4\"test error\"")
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleBinaryEvent() {
let expect = expectation(description: "handled binary event")
socket.on("test") {data, ack in
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)
waitForExpectations(timeout: 3, handler: nil)
}
func testHandleMultipleBinaryEvent() {
let expect = expectation(description: "handled multiple binary event")
socket.on("test") {data, ack in
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)
waitForExpectations(timeout: 3, handler: nil)
}
func testSocketManager() {
let manager = SocketClientManager.sharedManager
manager["test"] = socket
XCTAssert(manager["test"] === socket, "failed to get socket")
manager["test"] = nil
XCTAssert(manager["test"] == nil, "socket not removed")
}
}
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
+19
View File
@@ -0,0 +1,19 @@
//
// SocketIO-iOS.h
// SocketIO-iOS
//
// Created by Nacho Soto on 7/11/15.
//
//
#import <UIKit/UIKit.h>
//! Project version number for SocketIO-iOS.
FOUNDATION_EXPORT double SocketIO_iOSVersionNumber;
//! Project version string for SocketIO-iOS.
FOUNDATION_EXPORT const unsigned char SocketIO_iOSVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SocketIO_iOS/PublicHeader.h>
-747
View File
@@ -1,747 +0,0 @@
//
// SocketEngine.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension String {
private var length:Int {
return count(self)
}
}
public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingTimer:NSTimer?
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
let logType = "SocketEngine"
var connected:Bool {
return self._connected
}
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var log = false
var pingInterval:Int?
var polling:Bool {
return self._polling
}
var sid = ""
var socketPath = ""
var urlPolling:String?
var urlWebSocket:String?
var websocket:Bool {
return self._websocket
}
var ws:WebSocket?
public enum PacketType:Int {
case OPEN = 0
case CLOSE = 1
case PING = 2
case PONG = 3
case MESSAGE = 4
case UPGRADE = 5
case NOOP = 6
init?(str:String?) {
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client:SocketEngineClient, sessionDelegate:NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: self.workQueue)
}
public convenience init(client:SocketEngineClient, opts:NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
self.forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
self.forcePolling = opts?["forcePolling"] as? Bool ?? false
self.cookies = opts?["cookies"] as? [NSHTTPCookie]
self.log = opts?["log"] as? Bool ?? false
self.socketPath = opts?["path"] as? String ?? ""
}
deinit {
SocketLogger.log("Engine is being deinit", client: self)
}
public func close(#fast:Bool) {
SocketLogger.log("Engine is being closed. Fast: \(fast)", client: self)
self.pingTimer?.invalidate()
self.closed = true
self.write("", withType: PacketType.CLOSE, withData: nil)
self.ws?.disconnect()
self.stopPolling()
if fast || self.polling {
self.client?.engineDidClose("Disconnect")
}
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if self.websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return (mutData, nil)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
if self.client == nil {
return ("", "")
}
let path = self.socketPath == "" ? "/socket.io" : self.socketPath
var url = "\(self.client!.socketURL)\(path)/?transport="
var urlPolling:String
var urlWebSocket:String
if self.client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" ").invertedSet
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocket(andConnect connect:Bool) {
self.ws = WebSocket(url: NSURL(string: self.urlWebSocket! + "&sid=\(self.sid)")!,
cookies: self.cookies)
self.ws?.queue = self.handleQueue
self.ws?.delegate = self
if connect {
self.ws?.connect()
}
}
private func doFastUpgrade() {
if self.waitingForPoll {
SocketLogger.err("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", client: self)
}
self.sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
self._websocket = true
self._polling = false
self.fastUpgrade = false
self.probing = false
self.flushProbeWait()
}
private func doPoll() {
if self.websocket || self.waitingForPoll || !self.connected {
return
}
self.waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
self.doRequest(req)
}
private func doRequest(req:NSMutableURLRequest) {
if !self.polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
SocketLogger.log("Doing polling request", client: self)
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil {
if self!.polling {
self?.handlePollingFailed(err.localizedDescription)
} else {
NSLog(err.localizedDescription)
}
return
}
SocketLogger.log("Got polling response", client: self!)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(self!.parseQueue) {[weak self] in
self?.parsePollingMessage(str)
}
}
self?.waitingForPoll = false
if self!.fastUpgrade {
self?.doFastUpgrade()
return
} else if !self!.closed && self!.polling {
self?.doPoll()
}}.resume()
}
private func flushProbeWait() {
SocketLogger.log("Flushing probe wait", client: self)
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
for waiter in self!.probeWait {
self?.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self?.probeWait.removeAll(keepCapacity: false)
if self?.postWait.count != 0 {
self?.flushWaitingForPostToWebSocket()
}
}
}
private func flushWaitingForPost() {
if self.postWait.count == 0 || !self.connected {
return
} else if self.websocket {
self.flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in self.postWait {
let len = count(packet)
postStr += "\(len):\(packet)"
}
self.postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
self.waitingForPost = true
SocketLogger.log("POSTing: \(postStr)", client: self)
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil && self!.polling {
self?.handlePollingFailed(err.localizedDescription)
return
} else if err != nil {
NSLog(err.localizedDescription)
return
}
self?.waitingForPost = false
dispatch_async(self!.emitQueue) {[weak self] in
if !self!.fastUpgrade {
self?.flushWaitingForPost()
self?.doPoll()
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in self.postWait {
self.ws?.writeString(msg)
}
self.postWait.removeAll(keepCapacity: true)
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
self._connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
// If cancelled we were already closing
if self.client == nil || reason == "cancelled" {
return
}
if !self.closed {
self.client?.didError(reason)
self.client?.engineDidClose(reason)
}
}
public func open(opts:[String: AnyObject]? = nil) {
if self.connected {
SocketLogger.err("Tried to open while connected", client: self)
self.client?.didError("Tried to open while connected")
return
}
SocketLogger.log("Starting engine", client: self)
SocketLogger.log("Handshaking", client: self)
self.closed = false
let (urlPolling, urlWebSocket) = self.createURLs(opts)
self.urlPolling = urlPolling
self.urlWebSocket = urlWebSocket
if self.forceWebsockets {
self._polling = false
self._websocket = true
self.createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
reqPolling.allHTTPHeaderFields = headers
}
self.doRequest(reqPolling)
}
// Translatation of engine.io-parser#decodePayload
private func parsePollingMessage(str:String) {
if str.length == 1 {
return
}
// println(str)
let strArray = Array(str)
var length = ""
var n = 0
var msg = ""
func testLength(length:String, inout n:Int) -> Bool {
if let num = length.toInt() {
n = num
return false
} else {
return true
}
}
for var i = 0, l = str.length; i < l; i = i &+ 1 {
let chr = String(strArray[i])
if chr != ":" {
length += chr
} else {
if length == "" || testLength(length, &n) {
SocketLogger.err("Parsing error: \(str)", client: self)
self.handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i&+1...i&+n])
if let lengthInt = length.toInt() {
if lengthInt != msg.length {
SocketLogger.err("parsing error: \(str)", client: self)
return
}
}
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
self?.parseEngineMessage(msg, fromPolling: true)
}
}
i += n
length = ""
}
}
}
private func parseEngineData(data:NSData) {
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
SocketLogger.log("Got message: \(message)", client: self)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1]))
if type == PacketType.MESSAGE {
// Remove message type
message.removeAtIndex(message.startIndex)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseSocketMessage(message)
}
} else if type == PacketType.NOOP {
self.doPoll()
return
} else if type == PacketType.PONG {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
return
} else if type == PacketType.OPEN {
var err:NSError?
message.removeAtIndex(message.startIndex)
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments,
error: &err) as? NSDictionary, let sid = json["sid"] as? String {
self.sid = sid
self._connected = true
if !self.forcePolling && !self.forceWebsockets {
self.createWebsocket(andConnect: true)
}
if let pingInterval = json["pingInterval"] as? Int {
self.pingInterval = pingInterval / 1000
}
} else {
self.client?.didError("Engine failed to handshake")
return
}
self.startPingTimer()
if !self.forceWebsockets {
self.doPoll()
}
return
} else if type == PacketType.CLOSE {
if self.client == nil {
return
}
if self.polling {
self.client!.engineDidClose("Disconnect")
}
return
} else if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
where self.client != nil {
// println("sending \(data)")
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
private func probeWebSocket() {
if self.websocketConnected {
self.sendWebSocketMessage("probe", withType: PacketType.PING)
}
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if self.probing {
self.probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
self.write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
func sendPing() {
self.write("", withType: PacketType.PING, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending poll: \(msg) as type: \(type.rawValue)", client: self)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
}
}
if !self.waitingForPost {
self.flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending ws: \(str) as type: \(type.rawValue)", client: self)
self.ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.writeData(data!)
}
}
}
}
// Starts the ping timer
private func startPingTimer() {
if self.pingInterval == nil {
return
}
self.pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self!.pingInterval!),
target: self!,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
func stopPolling() {
self.session.invalidateAndCancel()
}
private func upgradeTransport() {
if self.websocketConnected {
SocketLogger.log("Upgrading transport to WebSockets", client: self)
// Do a fast upgrade
// At this point, we should not send anymore polling messages-
self.fastUpgrade = true
self.sendPollMessage("", withType: PacketType.NOOP)
}
}
/**
Write a message, independent of transport.
*/
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
if self!.websocket {
SocketLogger.log("Writing ws: \(msg):\(data)", client: self!)
self?.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
SocketLogger.log("Writing poll: \(msg):\(data)", client: self!)
self?.sendPollMessage(msg, withType: type, datas: data)
}
}
}
/**
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
*/
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
if let pType = PacketType(rawValue: type) {
var arr = ContiguousArray<NSData>()
if data != nil {
for d in data! {
arr.append(d as! NSData)
}
}
self.write(msg, withType: pType, withData: arr)
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
if !self.forceWebsockets {
self.probing = true
self.probeWebSocket()
} else {
self._connected = true
self.probing = false
self._polling = false
}
}
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.closed {
self.client?.engineDidClose("Disconnect")
return
}
if self.websocket {
self.pingTimer?.invalidate()
self._connected = false
self._websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
self.client?.didError(reason)
}
self.client?.engineDidClose(reason)
} else {
self.flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
-507
View File
@@ -1,507 +0,0 @@
//
// SocketIOClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 11/23/14.
//
// 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
public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient {
private lazy var params = [String: AnyObject]()
private var anyHandler:((SocketAnyEvent) -> Void)?
private var _closed = false
private var _connected = false
private var _connecting = false
private var currentReconnectAttempt = 0
private var handlers = ContiguousArray<SocketEventHandler>()
private var paramConnect = false
private var _secure = false
private var _sid:String?
private var _reconnecting = false
private var reconnectTimer:NSTimer?
let reconnectAttempts:Int!
let logType = "SocketClient"
var ackHandlers = SocketAckManager()
var currentAck = -1
var log = false
var waitingData = ContiguousArray<SocketPacket>()
var sessionDelegate:NSURLSessionDelegate?
public let socketURL:String
public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL)
public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
public var closed:Bool {
return self._closed
}
public var connected:Bool {
return self._connected
}
public var connecting:Bool {
return self._connecting
}
public var engine:SocketEngine?
public var nsp = "/"
public var opts:[String: AnyObject]?
public var reconnects = true
public var reconnecting:Bool {
return self._reconnecting
}
public var reconnectWait = 10
public var secure:Bool {
return self._secure
}
public var sid:String? {
return self._sid
}
/**
Create a new SocketIOClient. opts can be omitted
*/
public init(var socketURL:String, opts:[String: AnyObject]? = nil) {
if socketURL["https://"].matches().count != 0 {
self._secure = true
}
socketURL = socketURL["http://"] ~= ""
socketURL = socketURL["https://"] ~= ""
self.socketURL = socketURL
self.opts = opts
// Set options
if opts != nil {
if let sessionDelegate = opts!["sessionDelegate"] as? NSURLSessionDelegate {
self.sessionDelegate = sessionDelegate
}
if let log = opts!["log"] as? Bool {
self.log = log
}
if var nsp = opts!["nsp"] as? String {
if nsp != "/" && nsp.hasPrefix("/") {
nsp.removeAtIndex(nsp.startIndex)
}
self.nsp = nsp
}
if let reconnects = opts!["reconnects"] as? Bool {
self.reconnects = reconnects
}
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts!["reconnectWait"] as? Int {
self.reconnectWait = abs(reconnectWait)
}
} else {
self.reconnectAttempts = -1
}
super.init()
}
public convenience init(socketURL:String, options:[String: AnyObject]?) {
self.init(socketURL: socketURL, opts: options)
}
deinit {
SocketLogger.log("Client is being deinit", client: self)
}
private func addEngine() {
SocketLogger.log("Adding engine", client: self)
self.engine = SocketEngine(client: self, opts: self.opts)
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close(#fast:Bool) {
SocketLogger.log("Closing socket", client: self)
self.reconnects = false
self._connecting = false
self._connected = false
self._reconnecting = false
self.engine?.close(fast: fast)
self.engine = nil
}
/**
Connect to the server.
*/
public func connect() {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
if self.connected {
return
}
self.addEngine()
self.engine?.open()
}
/**
Connect to the server with params that will be passed on connection.
*/
public func connectWithParams(params:[String: AnyObject]) {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
if self.connected {
return
}
self.params = params
self.paramConnect = true
self.addEngine()
self.engine?.open(opts: params)
}
private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++self.currentAck] timeout, callback in
if self == nil {
return
}
self?.ackHandlers.addAck(ack, callback: callback)
dispatch_async(self!.emitQueue) {
self?._emit(event, items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
self?.ackHandlers.timeoutAck(ack)
}
}
}
}
func didConnect() {
SocketLogger.log("Socket connected", client: self)
self._closed = false
self._connected = true
self._connecting = false
self._reconnecting = false
self.currentReconnectAttempt = 0
self.reconnectTimer?.invalidate()
self.reconnectTimer = nil
self._sid = self.engine?.sid
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.handleEvent("connect", data: nil, isInternalMessage: false)
}
func didDisconnect(reason:String) {
if self.closed {
return
}
SocketLogger.log("Disconnected: \(reason)", client: self)
self._closed = true
self._connected = false
self.reconnects = false
self._connecting = false
self._reconnecting = false
// Make sure the engine is actually dead.
self.engine?.close(fast: true)
self.handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason:AnyObject) {
SocketLogger.err("Error: \(reason)", client: self)
self.handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect(#fast:Bool) {
self.close(fast: fast)
}
/**
Send a message to the server
*/
public func emit(event:String, _ items:AnyObject...) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event:String, withItems items:[AnyObject]) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
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 {
if !self.connected {
return createOnAck(event, items: items)
}
return self.createOnAck(event, items: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback {
if !self.connected {
return self.createOnAck(event, items: items)
}
return self.createOnAck(event, items: items)
}
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
if !self.connected {
return
}
let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createMessageForEvent(event)
SocketLogger.log("Emitting: \(str)", client: self)
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
self.engine?.send(str, withData: packet.binary)
} else {
self.engine?.send(str, withData: nil)
}
}
// If the server wants to know that the client received data
func emitAck(ack:Int, withData args:[AnyObject]) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createAck()
SocketLogger.log("Emitting Ack: \(str)", client: self!)
if packet.type == SocketPacket.PacketType.BINARY_ACK {
self?.engine?.send(str, withData: packet.binary)
} else {
self?.engine?.send(str, withData: nil)
}
}
}
public func engineDidClose(reason:String) {
self._connected = false
self._connecting = false
if self.closed || !self.reconnects {
self.didDisconnect("Engine closed")
} else if !self.reconnecting {
self.handleEvent("reconnect", data: [reason], isInternalMessage: true)
self.tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack:Int, data:AnyObject?) {
SocketLogger.log("Handling ack: \(ack) with data: \(data)", client: self)
self.ackHandlers.executeAck(ack,
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil) {
// println("Should do event: \(event) with data: \(data)")
if !self.connected && !isInternalMessage {
return
}
SocketLogger.log("Handling event: \(event) with data: \(data)", client: self)
if self.anyHandler != nil {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
}
}
for handler in self.handlers {
if handler.event == event {
if ack != nil {
handler.executeCallback(data, withAck: ack!, withSocket: self)
} else {
handler.executeCallback(data)
}
}
}
}
func joinNamespace() {
SocketLogger.log("Joining namespace", client: self)
if self.nsp != "/" {
self.engine?.send("0/\(self.nsp)", withData: nil)
}
}
/**
Removes handler(s)
*/
public func off(event:String) {
SocketLogger.log("Removing handler for event: \(event)", client: self)
self.handlers = self.handlers.filter {$0.event == event ? false : true}
}
/**
Adds a handler for an event.
*/
public func on(name:String, callback:NormalCallback) {
SocketLogger.log("Adding handler for event: \(name)", client: self)
let handler = SocketEventHandler(event: name, callback: callback)
self.handlers.append(handler)
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler:(SocketAnyEvent) -> Void) {
self.anyHandler = handler
}
/**
Same as connect
*/
public func open() {
self.connect()
}
public func parseSocketMessage(msg:String) {
SocketParser.parseSocketMessage(msg, socket: self)
}
public func parseBinaryData(data:NSData) {
SocketParser.parseBinaryData(data, socket: self)
}
/**
Trieds to reconnect to the server.
*/
public func reconnect() {
self._connected = false
self._connecting = false
self._reconnecting = false
self.engine?.stopPolling()
self.tryReconnect()
}
// We lost connection and should attempt to reestablish
@objc private func tryReconnect() {
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
self.didDisconnect("Reconnect Failed")
return
} else if self.connected {
self._connecting = false
self._reconnecting = false
return
}
if self.reconnectTimer == nil {
SocketLogger.log("Starting reconnect", client: self)
self._reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
}
}
SocketLogger.log("Trying to reconnect", client: self)
self.handleEvent("reconnectAttempt", data: [self.reconnectAttempts - self.currentReconnectAttempt],
isInternalMessage: true)
self.currentReconnectAttempt++
if self.paramConnect {
self.connectWithParams(self.params)
} else {
self.connect()
}
}
}
-233
View File
@@ -1,233 +0,0 @@
//
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
final class SocketPacket: Printable {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var description:String {
var better = "SocketPacket {type: ~~0; data: ~~1; " +
"id: ~~2; placeholders: ~~3;}"
better = better["~~0"] ~= (self.type != nil ? String(self.type!.rawValue) : "nil")
better = better["~~1"] ~= (self.data != nil ? "\(self.data!)" : "nil")
better = better["~~2"] ~= (self.id != nil ? String(self.id!) : "nil")
better = better["~~3"] ~= (self.placeholders != nil ? String(self.placeholders!) : "nil")
return better
}
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:PacketType?
enum PacketType:Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init?(str:String) {
if let int = str.toInt(), raw = PacketType(rawValue: int) {
self = raw
} else {
return nil
}
}
}
init(type:PacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
if self.placeholders == self.currentPlace {
return true
}
self.binary.append(data)
self.currentPlace++
if self.placeholders == self.currentPlace {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
let message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = PacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = PacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
self.type = PacketType.ACK
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
self.type = PacketType.BINARY_ACK
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String + ","
} else if arg is String {
message += "\"\(arg)\","
} else if arg is NSNull {
message += "null,"
} else {
message += "\(arg),"
}
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String, num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
-267
View File
@@ -1,267 +0,0 @@
//
// SocketParser.swift
// Socket.IO-Swift
//
// 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
class SocketParser {
private static let shredder = SocketParser.PacketShredder()
// Translation of socket.io-parser#deconstructPacket
private final class PacketShredder {
var buf = ContiguousArray<NSData>()
func shred(data:AnyObject) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
return placeholder
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = shred(arr[i])
}
return newArr
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in newDict {
newDict[key as! NSCopying] = shred(value)
}
return newDict
} else {
return data
}
}
func deconstructPacket(packet:SocketPacket) {
if packet.data == nil {
return
}
var data = packet.data!
for i in 0..<data.count {
if data[i] is NSArray || data[i] is NSDictionary {
data[i] = shred(data[i])
} else if let bin = data[i] as? NSData {
data[i] = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
}
}
packet.data = data
packet.binary = buf
buf.removeAll(keepCapacity: true)
}
}
// Translation of socket.io-client#decodeString
static func parseString(str:String) -> SocketPacket? {
let arr = Array(str)
let type = String(arr[0])
if arr.count == 1 {
return SocketPacket(type: SocketPacket.PacketType(str: type))
}
var id = nil as Int?
var nsp = ""
var i = 0
var placeholders = -1
if type == "5" || type == "6" {
var buf = ""
while arr[++i] != "-" {
buf += String(arr[i])
if i == arr.count {
break
}
}
if let holders = buf.toInt() where arr[i] == "-" {
placeholders = holders
} else {
NSLog("Error parsing \(str)")
return nil
}
}
if arr[i + 1] == "/" {
while ++i < arr.count {
let c = arr[i]
if c == "," {
break
}
nsp += String(c)
}
}
if i + 1 >= arr.count {
return SocketPacket(type: SocketPacket.PacketType(str: type),
nsp: nsp, placeholders: placeholders, id: id)
}
let next = String(arr[i + 1])
if next.toInt() != nil {
var c = ""
while ++i < arr.count {
if let int = String(arr[i]).toInt() {
c += String(arr[i])
} else {
--i
break
}
}
id = c.toInt()
}
if ++i < arr.count {
let d = String(arr[i...arr.count-1])
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = SocketParser.parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
return SocketPacket(type: SocketPacket.PacketType(str: type), data: data,
nsp: nsp, placeholders: placeholders, id: id)
}
return nil
}
// Parses data for events
static func parseData(data:String) -> AnyObject? {
var err:NSError?
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers, error: &err)
if err != nil {
// println(err)
return nil
}
return parsed
}
static func parseForEmit(packet:SocketPacket) {
shredder.deconstructPacket(packet)
}
// Parses messages recieved
static func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
if stringMessage == "" {
return
}
func checkNSP(nsp:String) -> Bool {
return nsp == "" && socket.nsp != "/"
}
SocketLogger.log("Parsing \(stringMessage)", client: socket, altType: "SocketParser")
let p:SocketPacket
if let pack = parseString(stringMessage) {
p = pack
} else {
socket.didError("Error parsing packet")
return
}
// Don't call SocketPacket.description unless we need to
if socket.log {
SocketLogger.log("Decoded packet as: \(p)", client: socket, altType: "SocketParser")
}
if p.type == SocketPacket.PacketType.EVENT {
if checkNSP(p.nsp) {
return
}
socket.handleEvent(p.getEvent(), data: p.data,
isInternalMessage: false, wantsAck: p.id)
} else if p.type == SocketPacket.PacketType.ACK {
if checkNSP(p.nsp) {
return
}
socket.handleAck(p.id!, data: p.data)
} else if p.type == SocketPacket.PacketType.BINARY_EVENT {
if checkNSP(p.nsp) {
return
}
socket.waitingData.append(p)
} else if p.type == SocketPacket.PacketType.BINARY_ACK {
if checkNSP(p.nsp) {
return
}
p.justAck = true
socket.waitingData.append(p)
} else if p.type == SocketPacket.PacketType.CONNECT {
if p.nsp == "" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
} else if p.type == SocketPacket.PacketType.DISCONNECT {
socket.didDisconnect("Got Disconnect")
} else if p.type == SocketPacket.PacketType.ERROR {
socket.didError(p.data == nil ? "Error" : p.data!)
}
}
static func parseBinaryData(data:NSData, socket:SocketIOClient) {
if socket.waitingData.count == 0 {
SocketLogger.err("Got data when not remaking packet", client: socket, altType: "SocketParser")
return
}
let shouldExecute = socket.waitingData[0].addData(data)
if !shouldExecute {
return
}
let packet = socket.waitingData.removeAtIndex(0)
packet.fillInPlaceholders()
if !packet.justAck {
socket.handleEvent(packet.getEvent(), data: packet.data,
wantsAck: packet.id)
} else {
socket.handleAck(packet.id!, data: packet.data)
}
}
}
-209
View File
@@ -1,209 +0,0 @@
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by John Holdsworth on 26/06/2014.
// Copyright (c) 2014 John Holdsworth.
//
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
//
// This code is in the public domain from:
// https://github.com/johnno1962/SwiftRegex
//
import Foundation
var swiftRegexCache = [String: NSRegularExpression]()
public class SwiftRegex: NSObject, BooleanType {
var target:String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
swiftRegexCache[pattern] = regex
self.regex = regex
}
else {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
super.init()
}
class func failure(message: String) {
println("SwiftRegex: "+message)
//assert(false,"SwiftRegex: failed")
}
final var targetRange: NSRange {
return NSRange(location: 0,length: count(target.utf16))
}
final func substring(range: NSRange) -> String? {
if ( range.location != NSNotFound ) {
return (target as NSString).substringWithRange(range)
} else {
return nil
}
}
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
return range(options: options).location != NSNotFound
}
public func range(options: NSMatchingOptions = nil) -> NSRange {
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
}
public func match(options: NSMatchingOptions = nil) -> String? {
return substring(range(options: options))
}
public func groups(options: NSMatchingOptions = nil) -> [String]? {
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
}
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
}
}
return groups
} else {
return nil
}
}
public subscript(groupno: Int) -> String? {
get {
return groups()?[groupno]
}
set(newValue) {
if newValue == nil {
return
}
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult(match,
inString: target as String, offset: 0, template: newValue!)
let mut = NSMutableString(string: target)
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
target = mut as String
}
}
}
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
as? [NSTextCheckingResult]
if matches != nil {
return matches!
} else {
return nil
}
}
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
return matchResults(options: options)!.map { $0.range }
}
public func matches(options: NSMatchingOptions = nil) -> [String] {
return matchResults(options: options)!.map( { self.substring($0.range)!})
}
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
return matchResults(options: options)!.map {self.groupsForMatch($0)}
}
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults(options: options)! {
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
}
return out
}
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
let matchRange = match.range
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
out.appendString( substitution(match, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
return out as String
}
public var boolValue: Bool {
return doesMatch()
}
}
extension String {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
}
}
extension String {
public subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern)
}
}
public func ~= (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range)!)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: nil)
}
-727
View File
@@ -1,727 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
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 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.
}
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
}
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 : Array<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 = 2048
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?
}
private var cookies:[NSHTTPCookie]?
public weak var delegate: WebSocketDelegate?
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var writeQueue: NSOperationQueue?
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
private var connectedBlock: ((Void) -> Void)? = nil
private var disconnectedBlock: ((NSError?) -> Void)? = nil
private var receivedTextBlock: ((String) -> Void)? = nil
private var receivedDataBlock: ((NSData) -> Void)? = nil
public var isConnected :Bool {
return connected
}
//init the websocket with a url
public init(url: NSURL) {
self.url = url
}
public convenience init(url: NSURL, cookies:[NSHTTPCookie]?) {
self.init(url: url)
self.cookies = cookies
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
//closure based instead of the delegate
public convenience init(url: NSURL, protocols: Array<String>, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void), data:(NSData) -> Void) {
self.init(url: url, protocols: protocols)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
receivedDataBlock = data
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), data:((NSData) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedDataBlock = data
}
///Connect to the websocket server on a background thread
public func connect() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
self.createHTTPRequest()
})
}
///disconnect from the websocket server
public func disconnect() {
writeError(CloseCode.Normal.rawValue)
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//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) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let str: NSString = url.absoluteString!
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1)
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
for (key, value) in headers {
self.addHeader(urlRequest, key: key as! String, val: value as! String)
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
}
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
self.addHeader(urlRequest, key: key, val: value)
}
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
self.initStreamsWithData(serializedRequest, Int(port!))
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest.takeUnretainedValue(),
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(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!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
}
if self.voipEnabled {
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
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 writeQueue != nil {
writeQueue!.waitUntilAllOperationsAreFinished()
}
inputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.close()
outputStream!.close()
inputStream = nil
outputStream = nil
isRunLoop = false
connected = false
dispatch_async(queue,{
if let disconnectBlock = self.disconnectedBlock {
disconnectBlock(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
connected = processHTTP(buffer, bufferLen: length)
if !connected {
dispatch_async(queue,{
//self.workaroundMethod()
let error = self.errorWithDetail("Invalid HTTP upgrade", code: 1)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
} else {
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() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if (fragBuffer != nil) {
var combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{
//self.workaroundMethod()
if let connectBlock = self.connectedBlock {
connectBlock()
}
self.delegate?.websocketDidConnect(self)
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
let headers: NSDictionary = cfHeaders.takeRetainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
var response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
var offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].byteSwapped
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 = UnsafePointer<UInt8>((buffer+offset))
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
let error = self.errorWithDetail("connection closed by server", code: code)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].byteSwapped
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].byteSwapped)
offset += sizeof(UInt16)
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = offset + Int(len)
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("first frame can't be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = offset + Int(len)
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///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 {
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{
if let textBlock = self.receivedTextBlock{
textBlock(str! as String)
}
self.delegate?.websocketDidReceiveMessage(self, text: str! as String)
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{
//self.workaroundMethod()
if let dataBlock = self.receivedDataBlock{
dataBlock(data)
}
self.delegate?.websocketDidReceiveData(self, data: data)
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.byteSwapped
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream in a
private func dequeueWrite(data: NSData, code: OpCode) {
if writeQueue == nil {
writeQueue = NSOperationQueue()
writeQueue!.maxConcurrentOperationCount = 1
}
writeQueue!.addOperationWithBlock {
//stream isn't ready, let's wait
var tries = 0;
while self.outputStream == nil || !self.connected {
if(tries < 5) {
sleep(1);
} else {
break;
}
tries++;
}
if !self.connected {
return
}
var offset = 2
UINT16_MAX
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = self.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).byteSwapped
offset += sizeof(UInt16)
} else {
buffer[1] = 127
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).byteSwapped
offset += sizeof(UInt64)
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if self.outputStream == nil {
break
}
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
if len == nil || len! < 0 {
var error: NSError?
if let streamError = self.outputStream?.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = self.errorWithDetail("output stream error during write", code: errCode)
}
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
break
} else {
total += len!
}
if total >= offset {
break
}
}
}
}
}
+258
View File
@@ -0,0 +1,258 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// SSLSecurity.swift
// Starscream
//
// Created by Dalton Cherry on 5/16/15.
// 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 Security
public class SSLCert : NSObject {
var certData: Data?
var key: SecKey?
/**
Designated init for certificates
- parameter data: is the binary data of the certificate
- returns: a representation security object to be used with
*/
public init(data: Data) {
self.certData = data
}
/**
Designated init for public keys
- parameter key: is the public key to be used
- returns: a representation security object to be used with
*/
public init(key: SecKey) {
self.key = key
}
}
public class SSLSecurity : NSObject {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [Data]? //the certificates
@nonobjc var pubKeys: [SecKey]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
Use certs from main app bundle
- 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 convenience init(usePublicKeys: Bool = false) {
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 as Data))
}
return certs
}
self.init(certs: certs, usePublicKeys: usePublicKeys)
}
/**
Designated init
- parameter keys: 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) {
self.usePublicKeys = usePublicKeys
super.init()
if self.usePublicKeys {
DispatchQueue.global(qos: .default).async {
let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in
var pubKeys = pubKeys
if let data = cert.certData, cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let key = cert.key {
pubKeys.append(key)
}
return pubKeys
}
self.pubKeys = pubKeys
self.isReady = true
}
} else {
let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in
var certificates = certificates
if let data = cert.certData {
certificates.append(data)
}
return certificates
}
self.certificates = certificates
self.isReady = true
}
}
/**
Valid the trust and domain name.
- parameter trust: is the serverTrust to validate
- parameter domain: is the CN domain to validate
- returns: if the key was successfully validated
*/
public func isValid(_ trust: SecTrust, domain: String?) -> Bool {
var tries = 0
while !self.isReady {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicy
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain as NSString?)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
let serverPubKeys = publicKeyChain(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
return true
}
}
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChain(trust)
var collect = [SecCertificate]()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert as CFData)!)
}
SecTrustSetAnchorCertificates(trust,collect as NSArray)
var result: SecTrustResultType = .unspecified
SecTrustEvaluate(trust,&result)
if result == .unspecified || result == .proceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount += 1
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
/**
Get the public key from a certificate data
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKey(_ data: Data) -> SecKey? {
guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil }
return extractPublicKey(cert, policy: SecPolicyCreateBasicX509())
}
/**
Get the public key from a certificate
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? {
var possibleTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
guard let trust = possibleTrust else { return nil }
var result: SecTrustResultType = .unspecified
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
/**
Get the certificate chain for the trust
- parameter trust: is the trust to lookup the certificate chain for
- returns: the certificate chain for the trust
*/
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!) as Data)
return certificates
}
return certificates
}
/**
Get the public key chain for the trust
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
- returns: the public keys from the certifcate chain for the trust
*/
@nonobjc func publicKeyChain(_ trust: SecTrust) -> [SecKey] {
let policy = SecPolicyCreateBasicX509()
let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [SecKey] in
var keys = keys
let cert = SecTrustGetCertificateAtIndex(trust, index)
if let key = extractPublicKey(cert!, policy: policy) {
keys.append(key)
}
return keys
}
return keys
}
}
@@ -1,8 +1,8 @@
//
// EventHandler.swift
// Socket.IO-Swift
// SocketAckEmitter.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/18/15.
// Created by Erik Little on 9/16/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,25 +24,24 @@
import Foundation
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {
socket.emitAck(num, withData: items)
public final class SocketAckEmitter : NSObject {
let socket: SocketIOClient
let ackNum: Int
init(socket: SocketIOClient, ackNum: Int) {
self.socket = socket
self.ackNum = ackNum
}
public func with(_ items: SocketData...) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, with: items)
}
public func with(_ items: [Any]) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, with: items)
}
}
final class SocketEventHandler {
let event:String!
let callback:NormalCallback?
init(event:String, callback:NormalCallback) {
self.event = event
self.callback = callback
}
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
}
}
}
@@ -1,6 +1,6 @@
//
// SocketAckManager.swift
// SocketIO-Swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/3/15.
//
@@ -24,51 +24,49 @@
import Foundation
private struct SocketAck: Hashable, Equatable {
let ack:Int
var callback:AckCallback!
var hashValue:Int {
private struct SocketAck : Hashable {
let ack: Int
var callback: AckCallback!
var hashValue: Int {
return ack.hashValue
}
init(ack:Int) {
init(ack: Int) {
self.ack = ack
}
init(ack:Int, callback:AckCallback) {
init(ack: Int, callback: @escaping AckCallback) {
self.ack = ack
self.callback = callback
}
}
private func <(lhs:SocketAck, rhs:SocketAck) -> Bool {
private func <(lhs: SocketAck, rhs: SocketAck) -> Bool {
return lhs.ack < rhs.ack
}
private func ==(lhs:SocketAck, rhs:SocketAck) -> Bool {
private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
return lhs.ack == rhs.ack
}
struct SocketAckManager {
private var acks = Set<SocketAck>(minimumCapacity: 1)
mutating func addAck(ack:Int, callback:AckCallback) {
self.acks.insert(SocketAck(ack: ack, callback: callback))
mutating func addAck(_ ack: Int, callback: @escaping AckCallback) {
acks.insert(SocketAck(ack: ack, callback: callback))
}
mutating func executeAck(ack:Int, items:[AnyObject]?) {
let callback = self.acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(items)
}
}
mutating func timeoutAck(ack:Int) {
let callback = self.acks.remove(SocketAck(ack: ack))
/// Should be called on handle queue
mutating func executeAck(_ ack: Int, with items: [Any], onQueue: DispatchQueue) {
let ack = acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(["NO ACK"])
}
onQueue.async() { ack?.callback(items) }
}
/// Should be called on handle queue
mutating func timeoutAck(_ ack: Int, onQueue: DispatchQueue) {
let ack = acks.remove(SocketAck(ack: ack))
onQueue.async() { ack?.callback?(["NO ACK"]) }
}
}
@@ -1,6 +1,6 @@
//
// SocketAnyEvent.swift
// Socket.IO-Swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/28/15.
//
@@ -24,12 +24,15 @@
import Foundation
@objc public final class SocketAnyEvent {
public let event:String!
public let items:NSArray?
public final class SocketAnyEvent : NSObject {
public let event: String
public let items: [Any]?
override public var description: String {
return "SocketAnyEvent: Event: \(event) items: \(items ?? nil)"
}
init(event:String, items:NSArray?) {
init(event: String, items: [Any]?) {
self.event = event
self.items = items
}
}
}
+82
View File
@@ -0,0 +1,82 @@
//
// SocketClientManager.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 6/11/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
/**
Experimental socket manager.
API subject to change.
Can be used to persist sockets across ViewControllers.
Sockets are strongly stored, so be sure to remove them once they are no
longer needed.
Example usage:
```
let manager = SocketClientManager.sharedManager
manager["room1"] = socket1
manager["room2"] = socket2
manager.removeSocket(socket: socket2)
manager["room1"]?.emit("hello")
```
*/
open class SocketClientManager : NSObject {
open static let sharedManager = SocketClientManager()
private var sockets = [String: SocketIOClient]()
open subscript(string: String) -> SocketIOClient? {
get {
return sockets[string]
}
set(socket) {
sockets[string] = socket
}
}
open func addSocket(_ socket: SocketIOClient, labeledAs label: String) {
sockets[label] = socket
}
open func removeSocket(withLabel label: String) -> SocketIOClient? {
return sockets.removeValue(forKey: label)
}
open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? {
var returnSocket: SocketIOClient?
for (label, dictSocket) in sockets where dictSocket === socket {
returnSocket = sockets.removeValue(forKey: label)
}
return returnSocket
}
open func removeSockets() {
sockets.removeAll()
}
}
+559
View File
@@ -0,0 +1,559 @@
//
// SocketEngine.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
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: 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: [HTTPCookie]?
public private(set) var doubleEncodeUTF8 = true
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
public private(set) var forcePolling = false
public private(set) var forceWebsockets = false
public private(set) var invalidated = false
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: URLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io/"
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: URLSessionDelegate?
private let logType = "SocketEngine"
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()
private var secure = false
private var security: SSLSecurity?
private var selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) {
self.client = client
self.url = url
for option in config {
switch option {
case let .connectParams(params):
connectParams = params
case let .cookies(cookies):
self.cookies = cookies
case let .doubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .extraHeaders(headers):
extraHeaders = headers
case let .sessionDelegate(delegate):
sessionDelegate = delegate
case let .forcePolling(force):
forcePolling = force
case let .forceWebsockets(force):
forceWebsockets = force
case let .path(path):
socketPath = path
if !socketPath.hasSuffix("/") {
socketPath += "/"
}
case let .voipEnabled(enable):
voipEnabled = enable
case let .secure(secure):
self.secure = secure
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: 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) {
do {
let dict = try msg.toNSDictionary()
guard let error = dict["message"] as? String else { return }
/*
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: 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(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)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(for: reqPolling as URLRequest)
}
private func createURLs() -> (URL, URL) {
if client == nil {
return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!)
}
var urlPolling = URLComponents(string: url.absoluteString)!
var urlWebSocket = URLComponents(string: url.absoluteString)!
var queryString = ""
urlWebSocket.path = socketPath
urlPolling.path = socketPath
if secure {
urlPolling.scheme = "https"
urlWebSocket.scheme = "wss"
} else {
urlPolling.scheme = "http"
urlWebSocket.scheme = "ws"
}
if connectParams != nil {
for (key, value) in connectParams! {
let keyEsc = key.urlEncode()!
let valueEsc = "\(value)".urlEncode()!
queryString += "&\(keyEsc)=\(valueEsc)"
}
}
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
return (urlPolling.url!, urlWebSocket.url!)
}
private func createWebsocketAndConnect() {
ws = WebSocket(url: urlWebSocketWithSid as URL)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.callbackQueue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
ws?.disableSSLCertValidation = selfSigned
ws?.security = security
ws?.connect()
}
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: reason) }
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return closeOutEngine(reason: reason)
}
if websocket {
sendWebSocketMessage("", withType: .close, withData: [])
closeOutEngine(reason: reason)
} else {
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) {
emitQueue.sync {
self.postWait.append(String(SocketEnginePacketType.close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(for: req) {_, _, _ in }
self.closeOutEngine(reason: reason)
}
}
public func doFastUpgrade() {
if waitingForPoll {
DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .upgrade, withData: [])
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
emitQueue.async {
for waiter in self.probeWait {
self.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
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.write(string: msg)
}
postWait.removeAll(keepingCapacity: false)
}
private func handleClose(_ reason: String) {
client?.engineDidClose(reason: reason)
}
private func handleMessage(_ message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
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
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(with message: String) {
pongsMissed = 0
// We should upgrade
if message == "3probe" {
upgradeTransport()
}
}
public func parseEngineData(_ data: Data) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
}
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 {
checkAndHandleEngineError(message)
return
}
if fromPolling && type != .noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
}
switch type {
case .message:
handleMessage(String(fixedString.characters.dropFirst()))
case .noop:
handleNOOP()
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
connected = false
fastUpgrade = false
polling = true
probing = false
invalidated = false
session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
sid = ""
waitingForPoll = false
waitingForPost = false
websocket = false
}
private func sendPing() {
guard connected else { return }
// Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose(reason: "Ping timeout")
return
}
guard let pingInterval = pingInterval else { return }
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: [])
// 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: [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)
self.sendWebSocketMessage(msg, withType: type, withData: data)
} else if !self.probing {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendPollMessage(msg, withType: type, withData: data)
} else {
self.probeWait.append((msg, type, data))
}
}
}
// Delegate methods
public func websocketDidConnect(socket: WebSocket) {
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
probing = false
if closed {
client?.engineDidClose(reason: "Disconnect")
return
}
if websocket {
connected = false
websocket = false
if let reason = error?.localizedDescription {
didError(reason: reason)
} else {
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")
}
}
@@ -1,6 +1,6 @@
//
// SocketEngineClient.swift
// Socket.IO-Swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/19/15.
//
@@ -25,14 +25,10 @@
import Foundation
@objc public protocol SocketEngineClient {
var handleQueue:dispatch_queue_attr_t! {get}
var emitQueue:dispatch_queue_attr_t! {get}
var socketURL:String {get}
var secure:Bool {get}
func didError(reason:AnyObject)
func engineDidClose(reason:String)
func parseSocketMessage(msg:String)
func parseBinaryData(data:NSData)
}
@objc public protocol SocketEngineClient {
func engineDidError(reason: String)
func engineDidClose(reason: String)
func engineDidOpen(reason: String)
func parseEngineMessage(_ msg: String)
func parseEngineBinaryData(_ data: Data)
}
@@ -1,8 +1,8 @@
//
// SocketFixUTF8.swift
// Socket.IO-Swift
// SocketEnginePacketType.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/16/15.
// Created by Erik Little on 10/7/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -25,14 +25,6 @@
import Foundation
func fixDoubleUTF8(inout name:String) {
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding)!
let latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding)!
name = latin1 as String
}
func doubleEncodeUTF8(inout str:String) {
let latin1 = str.dataUsingEncoding(NSUTF8StringEncoding)!
let utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding)!
str = utf8 as String
}
@objc public enum SocketEnginePacketType : Int {
case open, close, ping, pong, message, upgrade, noop
}
+232
View File
@@ -0,0 +1,232 @@
//
// SocketEnginePollable.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/15/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
/// Protocol that is used to implement socket.io polling support
public protocol SocketEnginePollable : SocketEngineSpec {
var invalidated: Bool { get }
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
var postWait: [String] { get set }
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 }
/// Because socket.io doesn't let you send two post request at the same time
/// we have to keep track if there's an outstanding post
var waitingForPost: Bool { get set }
func doPoll()
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data])
func stopPolling()
}
// Default polling methods
extension SocketEnginePollable {
private func addHeaders(for req: URLRequest) -> URLRequest {
var req = req
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
return req
}
func createRequestForPostWithPostWait() -> URLRequest {
defer { postWait.removeAll(keepingCapacity: true) }
var postStr = ""
for packet in postWait {
let len = packet.characters.count
postStr += "\(len):\(packet)"
}
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
var req = URLRequest(url: urlPollingWithSid)
let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
req = addHeaders(for: req)
req.httpMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
req.httpBody = postData
req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
return req as URLRequest
}
public func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
waitingForPoll = true
var req = URLRequest(url: urlPollingWithSid)
req = addHeaders(for: req)
doLongPoll(for: req )
}
func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
if !polling || closed || invalidated || fastUpgrade {
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTask(with: req, completionHandler: callback).resume()
}
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(reason: err?.localizedDescription ?? "Error")
}
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: String.Encoding.utf8) {
this.parseQueue.async {
this.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
let req = createRequestForPostWithPostWait()
waitingForPost = true
DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
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(reason: err?.localizedDescription ?? "Error")
}
return
}
this.waitingForPost = false
this.emitQueue.async {
if !this.fastUpgrade {
this.flushWaitingForPost()
this.doPoll()
}
}
}
}
func parsePollingMessage(_ str: String) {
guard str.characters.count != 1 else { return }
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilOccurence(of: ":")) {
let str = reader.read(count: n)
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
} else {
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
break
}
}
}
/// Send polling message.
/// Only call on emitQueue
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
if doubleEncodeUTF8 {
fixedMessage = doubleEncodeUTF8(message)
} else {
fixedMessage = message
}
postWait.append(String(type.rawValue) + fixedMessage)
for data in datas {
if case let .right(bin) = createBinaryDataForSend(using: data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
public func stopPolling() {
waitingForPoll = false
waitingForPost = false
session?.finishTasksAndInvalidate()
}
}
+115
View File
@@ -0,0 +1,115 @@
//
// SocketEngineSpec.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/7/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
@objc public protocol SocketEngineSpec {
weak var client: SocketEngineClient? { get set }
var closed: Bool { get }
var connected: Bool { get }
var connectParams: [String: Any]? { get set }
var doubleEncodeUTF8: Bool { get }
var cookies: [HTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: DispatchQueue { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: DispatchQueue { get }
var handleQueue: DispatchQueue { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: URL { get }
var urlWebSocket: URL { get }
var websocket: Bool { get }
var ws: WebSocket? { get }
init(client: SocketEngineClient, url: URL, options: NSDictionary?)
func connect()
func didError(reason: String)
func disconnect(reason: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func parseEngineData(_ data: Data)
func parseEngineMessage(_ message: String, fromPolling: Bool)
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data])
}
extension SocketEngineSpec {
var urlPollingWithSid: URL {
var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
return com.url!
}
var urlWebSocketWithSid: URL {
var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
return com.url!
}
func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
if websocket {
var byteArray = [UInt8](repeating: 0x4, count: 1)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.append(data)
return .left(mutData as Data)
} else {
let str = "b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
return .right(str)
}
}
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.data(using: String.Encoding.isoLatin1),
let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) {
return latin1 as String
} else {
return string
}
}
/// Send an engine message (4)
func send(_ msg: String, withData datas: [Data]) {
write(msg, withType: .message, withData: datas)
}
}
+62
View File
@@ -0,0 +1,62 @@
//
// SocketEngineWebsocket.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/15/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
/// Protocol that is used to implement socket.io WebSocket support
public protocol SocketEngineWebsocket : SocketEngineSpec, WebSocketDelegate {
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: [])
}
}
/// Send message on WebSockets
/// Only call on emitQueue
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: Data) {
parseEngineData(data)
}
}
@@ -1,8 +1,8 @@
//
// SocketTypes.swift
// SocketIO-Swift
// EventHandler.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/8/15.
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -24,11 +24,12 @@
import Foundation
// @objc_block is undocumented, but is used because Swift assumes that all
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
// And the way things are done here, the bridging fails to copy the block in
// SocketAckMap#addAck
public typealias AckCallback = @objc_block (NSArray?) -> Void
public typealias AckEmitter = (AnyObject...) -> Void
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
struct SocketEventHandler {
let event: String
let id: UUID
let callback: NormalCallback
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)
}
}
+458
View File
@@ -0,0 +1,458 @@
//
// SocketIOClient.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 11/23/14.
//
// 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
public final class SocketIOClient : NSObject, SocketEngineClient, SocketParsable {
public let socketURL: URL
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.notConnected {
didSet {
switch status {
case .connected:
reconnecting = false
currentReconnectAttempt = 0
default:
break
}
}
}
public var forceNew = false
public var nsp = "/"
public var config: SocketIOClientConfiguration
public var reconnects = true
public var reconnectWait = 10
private let ackQueue = DispatchQueue(label: "com.socketio.ackQueue", attributes: [])
private let emitQueue = DispatchQueue(label: "com.socketio.emitQueue", attributes: [])
private let logType = "SocketIOClient"
private let parseQueue = DispatchQueue(label: "com.socketio.parseQueue", attributes: [])
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var ackHandlers = SocketAckManager()
private var reconnecting = false
private(set) var currentAck = -1
private(set) var handleQueue = DispatchQueue.main
private(set) var reconnectAttempts = -1
var waitingPackets = [SocketPacket]()
public var sid: String? {
return nsp + "#" + (engine?.sid ?? "")
}
/// Type safe way to create a new SocketIOClient. opts can be omitted
public init(socketURL: URL, config: SocketIOClientConfiguration = []) {
self.config = config
self.socketURL = socketURL
if socketURL.absoluteString.hasPrefix("https://") {
self.config.insert(.secure(true))
}
for option in config {
switch option {
case let .reconnects(reconnects):
self.reconnects = reconnects
case let .reconnectAttempts(attempts):
reconnectAttempts = attempts
case let .reconnectWait(wait):
reconnectWait = abs(wait)
case let .nsp(nsp):
self.nsp = nsp
case let .log(log):
DefaultSocketLogger.Logger.log = log
case let .logger(logger):
DefaultSocketLogger.Logger = logger
case let .handleQueue(queue):
handleQueue = queue
case let .forceNew(force):
forceNew = force
default:
continue
}
}
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, config: NSDictionary?) {
self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
engine?.disconnect(reason: "Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType, args: "")
engine = SocketEngine(client: self, url: socketURL, config: config)
return engine!
}
/// Connect to the server.
public func connect() {
connect(timeoutAfter: 0, withHandler: nil)
}
/// 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 {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
return
}
status = .connecting
if engine == nil || forceNew {
addEngine().connect()
} else {
engine?.connect()
}
guard timeoutAfter != 0 else { return }
let time = DispatchTime.now() + Double(Int64(timeoutAfter) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
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: [Any]) -> OnAckCallback {
currentAck += 1
return {[weak self, ack = currentAck] timeout, callback in
guard let this = self else { return }
this.ackQueue.sync() {
this.ackHandlers.addAck(ack, callback: callback)
}
this._emit(items, ack: ack)
if timeout != 0 {
let time = DispatchTime.now() + Double(Int64(timeout * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
this.handleQueue.asyncAfter(deadline: time) {
this.ackHandlers.timeoutAck(ack, onQueue: this.handleQueue)
}
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .connected
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: [], isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .disconnected else { return }
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
reconnecting = false
status = .disconnected
// Make sure the engine is actually dead.
engine?.disconnect(reason: reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// Disconnects the socket.
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
didDisconnect(reason: "Disconnect")
}
/// Send a message to the server
public func emit(_ event: String, _ items: SocketData...) {
emit(event, with: items)
}
/// Same as emit, but meant for Objective-C
public func emit(_ event: String, with items: [Any]) {
guard status == .connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
_emit([event] + items)
}
/// 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: SocketData...) -> OnAckCallback {
return emitWithAck(event, with: items)
}
/// Same as emitWithAck, but for Objective-C
public func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback {
return createOnAck([event] + items)
}
private 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
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: self.nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
// If the server wants to know that the client received data
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()
if status != .disconnected {
status = .notConnected
}
if status == .disconnected || !reconnects {
didDisconnect(reason: reason)
} else if !reconnecting {
reconnecting = true
tryReconnect(reason: reason)
}
}
/// error
public func engineDidError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: [reason], isInternalMessage: true)
}
public func engineDidOpen(reason: String) {
DefaultSocketLogger.Logger.log(reason, type: "SocketEngineClient")
}
// Called when the socket gets an ack for something it sent
func handleAck(_ ack: Int, data: [Any]) {
guard status == .connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, 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: [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)
handleQueue.async {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(with: data, withAck: ack, withSocket: self)
}
}
}
/// Leaves nsp and goes back to /
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: [])
nsp = "/"
}
}
/// Joins namespace
public func joinNamespace(_ namespace: String) {
nsp = namespace
if nsp != "/" {
DefaultSocketLogger.Logger.log("Joining namespace", type: logType)
engine?.send("0\(nsp)", withData: [])
}
}
/// Removes handler(s) based on name
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: UUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id)
handlers = handlers.filter({ $0.id != id })
}
/// Adds a handler for an event.
/// Returns: A unique id for the handler
@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: UUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/// Adds a single-use handler for an event.
/// Returns: A unique id for the handler
@discardableResult
public func once(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = UUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else { return }
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/// Adds a handler that will be called on every event.
public func onAny(_ handler: @escaping (SocketAnyEvent) -> Void) {
anyHandler = handler
}
public func parseEngineMessage(_ msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
parseQueue.async { self.parseSocketMessage(msg) }
}
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(reason: "manual reconnect")
}
/// Removes all handlers.
/// Can be used after disconnecting to break any potential remaining retain cycles.
public func removeAllHandlers() {
handlers.removeAll(keepingCapacity: false)
}
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() {
guard reconnecting else { return }
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
return didDisconnect(reason: "Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [(reconnectAttempts - currentReconnectAttempt)], isInternalMessage: true)
currentReconnectAttempt += 1
connect()
let deadline = DispatchTime.now() + Double(Int64(UInt64(reconnectWait) * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: deadline, execute: _tryReconnect)
}
// Test properties
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .connected
}
func setTestEngine(_ engine: SocketEngineSpec?) {
self.engine = engine
}
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>.Generator
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)
}
}
+154
View File
@@ -0,0 +1,154 @@
//
// SocketIOClientOption .swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/17/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol ClientOption : CustomStringConvertible, Equatable {
func getSocketIOOptionValue() -> Any
}
public enum SocketIOClientOption : ClientOption {
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:
description = "connectParams"
case .cookies:
description = "cookies"
case .doubleEncodeUTF8:
description = "doubleEncodeUTF8"
case .extraHeaders:
description = "extraHeaders"
case .forceNew:
description = "forceNew"
case .forcePolling:
description = "forcePolling"
case .forceWebsockets:
description = "forceWebsockets"
case .handleQueue:
description = "handleQueue"
case .log:
description = "log"
case .logger:
description = "logger"
case .nsp:
description = "nsp"
case .path:
description = "path"
case .reconnects:
description = "reconnects"
case .reconnectAttempts:
description = "reconnectAttempts"
case .reconnectWait:
description = "reconnectWait"
case .secure:
description = "secure"
case .selfSigned:
description = "selfSigned"
case .security:
description = "security"
case .sessionDelegate:
description = "sessionDelegate"
case .voipEnabled:
description = "voipEnabled"
}
return description
}
func getSocketIOOptionValue() -> Any {
let value: Any
switch self {
case let .connectParams(params):
value = params
case let .cookies(cookies):
value = cookies
case let .doubleEncodeUTF8(encode):
value = encode
case let .extraHeaders(headers):
value = headers
case let .forceNew(force):
value = force
case let .forcePolling(force):
value = force
case let .forceWebsockets(force):
value = force
case let .handleQueue(queue):
value = queue
case let .log(log):
value = log
case let .logger(logger):
value = logger
case let .nsp(nsp):
value = nsp
case let .path(path):
value = path
case let .reconnects(reconnects):
value = reconnects
case let .reconnectAttempts(attempts):
value = attempts
case let .reconnectWait(wait):
value = wait
case let .secure(secure):
value = secure
case let .security(security):
value = security
case let .selfSigned(signed):
value = signed
case let .sessionDelegate(delegate):
value = delegate
case let .voipEnabled(enabled):
value = enabled
}
return value
}
}
public func ==(lhs: SocketIOClientOption, rhs: SocketIOClientOption) -> Bool {
return lhs.description == rhs.description
}
@@ -1,8 +1,8 @@
//
// SocketLogger.swift
// SocketIO-Swift
// SocketIOClientSpec.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/11/15.
// Created by Erik Little on 1/3/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
@@ -22,33 +22,22 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol SocketLogClient {
var log:Bool {get set}
var logType:String {get}
protocol SocketIOClientSpec : class {
var nsp: String { get set }
var waitingPackets: [SocketPacket] { get set }
func didConnect()
func didDisconnect(reason: String)
func didError(reason: String)
func handleAck(_ ack: Int, data: [Any])
func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(_ namespace: String)
}
final class SocketLogger {
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
static func log(message:String, client:SocketLogClient, altType:String? = nil) {
if !client.log {
return
}
extension SocketIOClientSpec {
func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason)
dispatch_async(printQueue) {[type = client.logType] in
NSLog("%@: %@", altType ?? type, message)
}
}
static func err(message:String, client:SocketLogClient, altType:String? = nil) {
if !client.log {
return
}
dispatch_async(printQueue) {[type = client.logType] in
NSLog("ERROR %@: %@", altType ?? type, message)
}
handleEvent("error", data: [reason], isInternalMessage: true, withAck: -1)
}
}
+32
View File
@@ -0,0 +1,32 @@
//
// SocketIOClientStatus.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 8/14/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// **NotConnected**: initial state
///
/// **Disconnected**: connected before
@objc public enum SocketIOClientStatus : Int {
case notConnected, disconnected, connecting, connected
}
+61
View File
@@ -0,0 +1,61 @@
//
// SocketLogger.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/11/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol SocketLogger : class {
/// Whether to log or not
var log: Bool { get set }
/// Normal log messages
func log(_ message: String, type: String, args: Any...)
/// Error Messages
func error(_ message: String, type: String, args: Any...)
}
public extension SocketLogger {
func log(_ message: String, type: String, args: Any...) {
abstractLog("LOG", message: message, type: type, args: args)
}
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: [Any]) {
guard log else { return }
let newArgs = args.map({arg -> CVarArg in String(describing: arg)})
let messageFormat = String(format: message, arguments: newArgs)
NSLog("\(logType) \(type): %@", messageFormat)
}
}
class DefaultSocketLogger : SocketLogger {
static var Logger: SocketLogger = DefaultSocketLogger()
var log = false
}
+213
View File
@@ -0,0 +1,213 @@
//
// SocketPacket.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
struct SocketPacket {
enum PacketType: Int {
case connect, disconnect, event, ack, error, binaryEvent, binaryAck
}
private let placeholders: Int
private static let logType = "SocketPacket"
let nsp: String
let id: Int
let type: PacketType
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 description: String {
return "SocketPacket {type: \(String(type.rawValue)); data: " +
"\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}"
}
var event: String {
return String(describing: data[0])
}
var packetString: String {
return createPacketString()
}
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
self.type = type
self.placeholders = placeholders
self.binary = binary
}
mutating func addData(_ data: Data) -> Bool {
if placeholders == binary.count {
return true
}
binary.append(data)
if placeholders == binary.count {
fillInPlaceholders()
return true
} else {
return false
}
}
private func completeMessage(_ message: String) -> String {
let restOfMessage: String
if data.count == 0 {
return message + "[]"
}
do {
let jsonSend = try data.toJSON()
guard let jsonString = String(data: jsonSend, encoding: .utf8) else { return message + "[]" }
restOfMessage = jsonString
} catch {
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
restOfMessage = "[]"
}
return message + restOfMessage
}
private func createPacketString() -> String {
let typeString = String(type.rawValue)
// 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)
}
// Called when we have all the binary data for a packet
// calls _fillInPlaceholders, which replaces placeholders with the
// corresponding binary
private mutating func fillInPlaceholders() {
data = data.map(_fillInPlaceholders)
}
// Helper method that looks for placeholders
// 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: Any) -> Any {
switch object {
case let dict as [String: Any]:
if dict["_placeholder"] as? Bool ?? false {
return binary[dict["num"] as! Int]
} else {
return dict.reduce([String: Any](), {cur, keyValue in
var cur = cur
cur[keyValue.0] = _fillInPlaceholders(keyValue.1)
return cur
})
}
case let arr as [Any]:
return arr.map(_fillInPlaceholders)
default:
return object
}
}
}
extension SocketPacket {
private static func findType(_ binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return .event
case 0 where ack:
return .ack
case _ where !ack:
return .binaryEvent
case _ where ack:
return .binaryAck
default:
return .error
}
}
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)
return packet
}
}
private extension SocketPacket {
// Recursive function that looks for NSData in collections
static func shred(_ data: Any, binary: inout [Data]) -> Any {
let placeholder = ["_placeholder": true, "num": binary.count] as [String : Any]
switch data {
case let bin as Data:
binary.append(bin)
return placeholder
case let arr as [Any]:
return arr.map({shred($0, binary: &binary)})
case let dict as [String: Any]:
return dict.reduce([String: Any](), {cur, keyValue in
var mutCur = cur
mutCur[keyValue.0] = shred(keyValue.1, binary: &binary)
return mutCur
})
default:
return data
}
}
// Removes binary data from emit data
// Returns a type containing the de-binaryed data and the binary
static func deconstructData(_ data: [Any]) -> ([Any], [Data]) {
var binary = [Data]()
return (data.map({shred($0, binary: &binary)}), binary)
}
}
+168
View File
@@ -0,0 +1,168 @@
//
// SocketParsable.swift
// Socket.IO-Client-Swift
//
// 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
protocol SocketParsable : SocketIOClientSpec {
func parseBinaryData(_ data: Data)
func parseSocketMessage(_ message: String)
}
extension SocketParsable {
private func isCorrectNamespace(_ nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(_ packetNamespace: String) {
if packetNamespace == "/" && nsp != "/" {
joinNamespace(nsp)
} else {
didConnect()
}
}
private func handlePacket(_ pack: SocketPacket) {
switch pack.type {
case .event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
case .ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .binaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .binaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
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)
}
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(_ message: String) -> Either<String, SocketPacket> {
var reader = SocketStringReader(message: message)
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
return .left("Invalid packet type")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .binaryEvent || type == .binaryAck {
if let holders = Int(reader.readUntilOccurence(of: "-")) {
placeholders = holders
} else {
return .left("Invalid packet")
}
}
if reader.currentCharacter == "/" {
namespace = reader.readUntilOccurence(of: ",")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
}
var idString = ""
if type == .error {
reader.advance(by: -1)
} else {
while reader.hasNext {
if let int = Int(reader.read(count: 1)) {
idString += String(int)
} else {
reader.advance(by: -2)
break
}
}
}
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, [Any]> {
do {
return .right(try data.toArray())
} catch {
return .left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(_ message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(_ data: Data) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingPackets[waitingPackets.count - 1].addData(data) else { return }
let packet = waitingPackets.removeLast()
if packet.type != .binaryAck {
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
}
}
+73
View File
@@ -0,0 +1,73 @@
//
// SocketStringReader.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 07.09.15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
struct SocketStringReader {
let message: String
var currentIndex: String.Index
var hasNext: Bool {
return currentIndex != message.endIndex
}
var currentCharacter: String {
return String(message[currentIndex])
}
init(message: String) {
self.message = message
currentIndex = message.startIndex
}
@discardableResult
mutating func advance(by: Int) -> String.Index {
currentIndex = message.characters.index(currentIndex, offsetBy: by)
return currentIndex
}
mutating func read(count: Int) -> String {
let readString = message[currentIndex..<message.characters.index(currentIndex, offsetBy: count)]
advance(by: count)
return readString
}
mutating func readUntilOccurence(of string: String) -> String {
let substring = message[currentIndex..<message.endIndex]
guard let foundRange = substring.range(of: string) else {
currentIndex = message.endIndex
return substring
}
advance(by: message.characters.distance(from: message.characters.startIndex, to: foundRange.lowerBound) + 1)
return substring.substring(to: foundRange.lowerBound)
}
mutating func readUntilEnd() -> String {
return read(count: message.characters.distance(from: currentIndex, to: message.endIndex))
}
}
+52
View File
@@ -0,0 +1,52 @@
//
// SocketTypes.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/8/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol SocketData {}
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
public typealias OnAckCallback = (_ timeoutAfter: UInt64, _ callback: @escaping AckCallback) -> Void
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data])
typealias ProbeWaitQueue = [Probe]
enum Either<E, V> {
case left(E)
case right(V)
}
+931
View File
@@ -0,0 +1,931 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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: Data)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket, data: Data?)
}
public 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: SSLSecurity?
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
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.
*/
public func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
isConnecting = 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.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
public func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
switch forceTimeout {
case .some(let seconds) where seconds > 0:
callbackQueue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [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 str: The string to write.
- parameter completion: The (optional) completion handler.
*/
public 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.
*/
public 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
*/
public 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)
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!) {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
} 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)
}
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
}
}
}
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 * 1000000 // wait 5 seconds before giving up
writeQueue.addOperation { [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.count)
}
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) {
let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject
let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if sec.isValid(trust as! SecTrust, domain: domain) {
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 as NSError?)
} else if eventCode == .endEncountered {
disconnectStream(nil)
}
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: NSError?) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
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
}
/**
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 {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
var combine = NSData(data: fragBuffer) as Data
combine.append(data)
work = combine
self.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:
connected = true
guard canDispatch else {return}
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)
}
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
}
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 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
}
var closeReason = "connection closed by server"
if payloadLen > 2 {
let len = Int(payloadLen - 2)
if len > 0 {
let bytes = baseAddress + offset
if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) {
closeReason = customCloseReason
} else {
code = CloseCode.protocolError.rawValue
}
}
}
doDisconnect(errorWithDetail(closeReason, 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 += 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)
}
let data: Data
if len < 0 {
len = 0
data = Data()
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
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) {
writeQueue.addOperation { [weak self] in
//stream isn't ready, let's wait
guard let s = self 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 true {
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
}
}
}
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
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()
}
}
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)