Compare commits

...
280 Commits
Author SHA1 Message Date
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 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
Lukas Schmidt 6a10f72443 Merge branch 'swift-2' 2015-09-11 10:22:47 +02:00
54 changed files with 3571 additions and 3146 deletions

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
.AppleDouble
.LSOverride
*.xcodeproj
.build/*
Packages/*
# Icon must end with two \r
Icon
+9 -1
View File
@@ -2,4 +2,12 @@ language: objective-c
xcode_project: Socket.IO-Client-Swift.xcodeproj # path to your xcodeproj folder
xcode_scheme: SocketIO-iOS
osx_image: xcode7
script: xcodebuild -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-iOS -sdk iphonesimulator build test CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
before_install:
- cd Socket.IO-Test-Server/
- npm install
- cd ..
install: node Socket.IO-Test-Server/main.js &
script: xctool -project Socket.IO-Client-Swift.xcodeproj -scheme SocketIO-Mac build test -parallelize
cache:
directories:
- Socket.IO-Test-Server/node_modules
+5
View File
@@ -0,0 +1,5 @@
import PackageDescription
let package = Package(
name: "SocketIOClientSwift"
)
+82 -42
View File
@@ -5,19 +5,19 @@ Socket.IO-client for iOS/OS X.
##Example
```swift
let socket = SocketIOClient(socketURL: "localhost:8080")
let socket = SocketIOClient(socketURL: "localhost:8080", options: [.Log(true), .ForcePolling(true)])
socket.on("connect") {data, ack in
print("socket connected")
}
socket.on("currentAmount") {data, ack in
if let cur = data?[0] as? Double {
if let cur = data[0] as? Double {
socket.emitWithAck("canUpdate", cur)(timeoutAfter: 0) {data in
socket.emit("update", ["amount": cur + 2.50])
}
ack?("Got your currentAmount", "dude")
ack.with("Got your currentAmount", "dude")
}
}
@@ -26,20 +26,20 @@ socket.connect()
##Objective-C Example
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:@{@"log": @YES, @"forcePolling": @YES}];
[socket onObjectiveC:@"connect" callback:^(NSArray* data, void (^ack)(NSArray*)) {
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
NSLog(@"socket connected");
}];
[socket onObjectiveC:@"currentAmount" callback:^(NSArray* data, void (^ack)(NSArray*)) {
[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(@[@"Got your currentAmount, ", @"dude"]);
[ack with:@[@"Got your currentAmount, ", @"dude"]];
}];
[socket connect];
@@ -60,20 +60,36 @@ If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer m
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 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.
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: 5)
]
)
```
Then import `import SocketIOClientSwift`.
Carthage
-----------------
Add this line to your `Cartfile`:
```
github "socketio/socket.io-client-swift" ~> 3.0.2 # Or latest version
github "socketio/socket.io-client-swift" ~> 5.2.2 # Or latest version
```
Run `carthage update --platform ios,macosx`.
Manually (iOS 7+)
-----------------
1. Copy the SocketIOClientSwift 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+)
------------------
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
@@ -83,7 +99,7 @@ source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 3.0.2' # Or latest version
pod 'Socket.IO-Client-Swift', '~> 5.2.2' # Or latest version
```
Install pods:
@@ -96,53 +112,77 @@ Import the module:
Swift:
```swift
import Socket_IO_Client_Swift
import SocketIOClientSwift
```
Objective-C:
```Objective-C
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
#import <SocketIOClientSwift/SocketIOClientSwift-Swift.h>
```
CocoaSeeds
-----------------
Add this line to your `Seedfile`:
```
github "socketio/socket.io-client-swift", "v5.2.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: String, options: Set<SocketIOClientOption> = [])` - Creates a new SocketIOClient. opts is a Set of SocketIOClientOption. 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: String, options: NSDictionary?)` - Same as above, but meant for Objective-C. See Options on how convert between SocketIOClientOptions and dictionary keys.
Options
-------
- `connectParams: [String: AnyObject]?` - Dictionary whose contents will be passed with the connection.
- `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 `"/"`. Connects to a namespace.
- `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.
- `logger: SocketLogger` If you wish to implement your own logger that conforms to SocketLogger you can pass it in here. Will use the default logging defined under the protocol otherwise.
- `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 `""`
- `extraHeaders: [String: String]?` - Adds custom headers to the initial request. Default is nil.
- `handleQueue: dispatch_queue_t` - The dispatch queue that handlers are run on. Default is the main queue.
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 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 ForcePolling(Bool) // `true` forces the client to use xhr-polling. Default is `false`
case ForceNew(Bool) // Will a create a new engine for each connect. Useful if you find a bug in the engine related to reconnects
case ForceWebsockets(Bool) // `true` forces the client to use WebSockets. Default is `false`
case Nsp(String) // The namespace to connect to. Must begin with /. Default is `/`
case Cookies([NSHTTPCookie]) // An array of NSHTTPCookies. Passed during the handshake. Default is nil.
case Log(Bool) // If `true` socket will log debug messages. Default is false.
case Logger(SocketLogger) // Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
case SessionDelegate(NSURLSessionDelegate) // Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
case Path(String) // If the server uses a custom path. ex: `"/swift"`. Default is `""`
case ExtraHeaders([String: String]) // Adds custom headers to the initial request. Default is nil.
case HandleQueue(dispatch_queue_t) // The dispatch queue that handlers are run on. Default is the main queue.
case VoipEnabled(Bool) // Only use this option if you're using the client with VoIP services. Changes the way the WebSocket is created. Default is false
case Secure(Bool) // If the connection should use TLS. Default is false.
case SelfSigned(Bool) // Sets WebSocket.selfSignedSSL (Don't do this, iOS will yell at you)
```
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. `onObjectiveC(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.
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.
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:Int, withTimeoutHandler handler:(() -> Void)?)` - Connect to the server. If it isn't connected after timeoutAfter seconds, the handler is called.
10. `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.
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()` - Causes the client to join nsp. Shouldn't need to be called unless you change nsp manually.
12. `joinNamespace(namespace: String)` - Causes the client to join namespace. Shouldn't need to be called unless you change namespaces manually.
13. `leaveNamespace()` - Causes the client to leave the nsp and go back to /
14. `off(event: String)` - Removes all event handlers for event.
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 = "3.0.2"
s.module_name = "SocketIOClientSwift"
s.version = "5.2.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 => 'v3.0.2' }
s.source_files = "SocketIOClientSwift/**/*.swift"
s.tvos.deployment_target = '9.0'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v5.2.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
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0640"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -37,10 +37,10 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -57,26 +57,29 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.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"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -85,16 +88,16 @@
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2371B51F18A00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-Mac"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0640"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -58,7 +58,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -80,7 +80,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -98,7 +98,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "572EF2181B51F16C00EEBB58"
BuildableName = "SocketIO.framework"
BuildableName = "SocketIOClientSwift.framework"
BlueprintName = "SocketIO-iOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
</BuildableReference>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425F9A1BA3A46000BDAAC1"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
@@ -28,7 +28,7 @@
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425FD81BA3A4F100BDAAC1"
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
BuildableName = "SocketIO-tvOSTests.xctest"
BlueprintName = "SocketIO-tvOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
@@ -46,7 +46,7 @@
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425FD81BA3A4F100BDAAC1"
BlueprintIdentifier = "57634A181BD9B46D00E19CD7"
BuildableName = "SocketIO-tvOSTests.xctest"
BlueprintName = "SocketIO-tvOSTests"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
@@ -56,7 +56,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425F9A1BA3A46000BDAAC1"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
@@ -78,7 +78,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425F9A1BA3A46000BDAAC1"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
@@ -96,7 +96,7 @@
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "57425F9A1BA3A46000BDAAC1"
BlueprintIdentifier = "576349FA1BD9B46A00E19CD7"
BuildableName = "SocketIO.framework"
BlueprintName = "SocketIO-tvOS"
ReferencedContainer = "container:Socket.IO-Client-Swift.xcodeproj">
+5 -3
View File
@@ -1,6 +1,8 @@
var app = require('express')()
var server = app.listen(6979)
var io = require('socket.io')(server)
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")
-1
View File
@@ -9,7 +9,6 @@
"author": "Lukas Schmidt",
"license": "MIT",
"dependencies": {
"express": "^4.13.1",
"socket.io": "^1.3.6"
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@@ -7,6 +7,7 @@
//
import XCTest
@testable import SocketIOClientSwift
class SocketAckManagerTest: XCTestCase {
var ackManager = SocketAckManager()
@@ -14,9 +15,8 @@ class SocketAckManagerTest: XCTestCase {
func testAddAcks() {
let callbackExpection = self.expectationWithDescription("callbackExpection")
let itemsArray = ["Hi", "ho"]
func callback(items: NSArray?) {
func callback(items: [AnyObject]) {
callbackExpection.fulfill()
items?.isEqualToArray(itemsArray)
}
ackManager.addAck(1, callback: callback)
ackManager.executeAck(1, items: itemsArray)
@@ -0,0 +1,140 @@
//
// SocketBasicPacketTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/7/15.
//
//
import XCTest
@testable import SocketIOClientSwift
class SocketBasicPacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
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 = ["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 testJSONEmit() {
let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let 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 = ["test", ["hello", 1, ["test": "test"]]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data])
}
func testMultipleBinaryEmit() {
let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data, data2])
}
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\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["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[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
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[{\"num\":0,\"_placeholder\":true}]"
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\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
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])
}
}
+77
View File
@@ -0,0 +1,77 @@
//
// SocketEngineTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/15/15.
//
//
import XCTest
@testable import SocketIOClientSwift
class SocketEngineTest: XCTestCase {
var client: SocketIOClient!
var engine: SocketEngine!
override func setUp() {
super.setUp()
client = SocketIOClient(socketURL: "")
engine = SocketEngine(client: client, url: "", options: nil)
client.setTestable()
}
func testBasicPollingMessage() {
let expectation = expectationWithDescription("Basic polling test")
client.on("blankTest") {data, ack in
expectation.fulfill()
}
engine.parsePollingMessage("15:42[\"blankTest\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testTwoPacketsInOnePollTest() {
let finalExpectation = expectationWithDescription("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 where gotBlank {
if str == "hello" {
finalExpectation.fulfill()
}
}
}
engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDoesErrorOnUnknownTransport() {
let finalExpectation = expectationWithDescription("Unknown Transport")
client.on("error") {data, ack in
if let error = data[0] as? String where error == "Unknown transport" {
finalExpectation.fulfill()
}
}
engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testEngineDoesErrorOnUnknownMessage() {
let finalExpectation = expectationWithDescription("Engine Errors")
client.on("error") {data, ack in
finalExpectation.fulfill()
}
engine.parseEngineMessage("afafafda", fromPolling: false)
waitForExpectationsWithTimeout(3, handler: nil)
}
}
-36
View File
@@ -1,36 +0,0 @@
//
// SocketIO_MacTests.swift
// SocketIO-MacTests
//
// Created by Nacho Soto on 7/11/15.
//
//
import Cocoa
import XCTest
class SocketIO_MacTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
@@ -0,0 +1,140 @@
//
// SocketNamespacePacketTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/11/15.
//
//
import XCTest
@testable import SocketIOClientSwift
class SocketNamespacePacketTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
func testEmpyEmit() {
let expectedSendString = "2/swift,[\"test\"]"
let sendData = ["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 = ["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 = ["test", "foo bar"]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testJSONEmit() {
let expectedSendString = "2/swift,[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testArrayEmit() {
let expectedSendString = "2/swift,[\"test\",[\"hello\",1,{\"test\":\"test\"}]]"
let sendData = ["test", ["hello", 1, ["test": "test"]]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
}
func testBinaryEmit() {
let expectedSendString = "51-/swift,[\"test\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["test", data]
let 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\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]"
let sendData = ["test", ["data1": data, "data2": data2]]
let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/swift", ack: false)
XCTAssertEqual(packet.packetString, expectedSendString)
XCTAssertEqual(packet.binary, [data, data2])
}
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\",{\"num\":0,\"_placeholder\":true}]"
let sendData = ["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[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]"
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[{\"num\":0,\"_placeholder\":true}]"
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\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]"
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])
}
}
@@ -7,19 +7,25 @@
//
import XCTest
@testable import SocketIOClientSwift
class SocketParserTest: XCTestCase {
let testSocket = SocketIOClient(socketURL: "")
//Format key: message; namespace-data-binary-id
static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
"25[\"test\"]": ("/", ["test"], [], 5),
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19),
"4/swift,": ("/swift", [], [], -1),
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1)]
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"41": ("/", [1], [], -1)]
func testDisconnect() {
let message = "1"
@@ -41,6 +47,16 @@ class SocketParserTest: XCTestCase {
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)
@@ -66,9 +82,24 @@ class SocketParserTest: XCTestCase {
validateParseResult(message)
}
func testErrorTypeString() {
let message = "4\"ERROR\""
validateParseResult(message)
}
func testErrorTypeInt() {
let message = "41"
validateParseResult(message)
}
func testInvalidInput() {
let message = "8"
XCTAssertNil(SocketParser.parseString(message))
switch testSocket.parseString(message) {
case .Left(_):
return
case .Right(_):
XCTFail("Created packet when shouldn't have")
}
}
func testGenericParser() {
@@ -81,10 +112,10 @@ class SocketParserTest: XCTestCase {
func validateParseResult(message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = SocketParser.parseString(message)
let packet = testSocket.parseString(message)
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
if let packet = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(str:type)!)
if case let .Right(packet) = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
XCTAssertEqual(packet.nsp, validValues.0)
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1))
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2))
@@ -98,7 +129,7 @@ class SocketParserTest: XCTestCase {
let keys = Array(SocketParserTest.packetTypes.keys)
measureBlock({
for item in keys.enumerate() {
SocketParser.parseString(item.element)
self.testSocket.parseString(item.element)
}
})
}
@@ -0,0 +1,145 @@
//
// SocketSideEffectTest.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/11/15.
//
//
import XCTest
@testable import SocketIOClientSwift
class SocketSideEffectTest: XCTestCase {
let data = "test".dataUsingEncoding(NSUTF8StringEncoding)!
let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)!
private var socket: SocketIOClient!
override func setUp() {
super.setUp()
socket = SocketIOClient(socketURL: "")
socket.setTestable()
}
func testInitialCurrentAck() {
XCTAssertEqual(socket.currentAck, -1)
}
func testFirstAck() {
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
XCTAssertEqual(socket.currentAck, 0)
}
func testSecondAck() {
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
socket.emitWithAck("test")(timeoutAfter: 0) {data in}
XCTAssertEqual(socket.currentAck, 1)
}
func testHandleAck() {
let expectation = expectationWithDescription("handled ack")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertEqual(data[0] as? String, "hello world")
expectation.fulfill()
}
socket.parseSocketMessage("30[\"hello world\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleAck2() {
let expectation = expectationWithDescription("handled ack2")
socket.emitWithAck("test")(timeoutAfter: 0) {data in
XCTAssertTrue(data.count == 2, "Wrong number of ack items")
expectation.fulfill()
}
socket.parseSocketMessage("61-0[{\"_placeholder\":true,\"num\":0},{\"test\":true}]")
socket.parseBinaryData(NSData())
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleEvent() {
let expectation = expectationWithDescription("handled event")
socket.on("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleOnceEvent() {
let expectation = expectationWithDescription("handled event")
socket.once("test") {data, ack in
XCTAssertEqual(data[0] as? String, "hello world")
XCTAssertEqual(self.socket.testHandlers.count, 0)
expectation.fulfill()
}
socket.parseSocketMessage("2[\"test\",\"hello world\"]")
waitForExpectationsWithTimeout(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 expectation = expectationWithDescription("Handled error")
socket.on("error") {data, ack in
if let error = data[0] as? String where error == "test error" {
expectation.fulfill()
}
}
socket.parseSocketMessage("4\"test error\"")
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleBinaryEvent() {
let expectation = expectationWithDescription("handled binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData {
XCTAssertEqual(data, self.data)
expectation.fulfill()
}
}
socket.parseSocketMessage("51-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]")
socket.parseBinaryData(data)
waitForExpectationsWithTimeout(3, handler: nil)
}
func testHandleMultipleBinaryEvent() {
let expectation = expectationWithDescription("handled multiple binary event")
socket.on("test") {data, ack in
if let dict = data[0] as? NSDictionary, data = dict["test"] as? NSData,
data2 = dict["test2"] as? NSData {
XCTAssertEqual(data, self.data)
XCTAssertEqual(data2, self.data2)
expectation.fulfill()
}
}
socket.parseSocketMessage("52-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0},\"test2\":{\"_placeholder\":true,\"num\":1}}]")
socket.parseBinaryData(data)
socket.parseBinaryData(data2)
waitForExpectationsWithTimeout(3, handler: nil)
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
-115
View File
@@ -1,115 +0,0 @@
//
// AbstractSocketTest.swift
// AbstractSocketTest.socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 02.08.15.
//
//
import XCTest
class AbstractSocketTest: XCTestCase {
static let testLocal = false
static let serverURL = AbstractSocketTest.testLocal ? "localhost:6979" : "milkbartube.com:6979"
static let TEST_TIMEOUT = 8.0
static var socket:SocketIOClient!
var testKind:TestKind?
func openConnection() {
guard AbstractSocketTest.socket.status == SocketIOClientStatus.NotConnected else {return}
weak var expection = self.expectationWithDescription("connect")
XCTAssertTrue(AbstractSocketTest.socket.status == SocketIOClientStatus.NotConnected)
AbstractSocketTest.socket.on("connect") {data, ack in
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connected)
XCTAssertFalse(AbstractSocketTest.socket.secure)
if let expection = expection {
expection.fulfill()
}
}
AbstractSocketTest.socket.connect()
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connecting)
waitForExpectationsWithTimeout(AbstractSocketTest.TEST_TIMEOUT, handler: nil)
}
func generateTestName(rawTestName:String) ->String {
return rawTestName + testKind!.rawValue
}
func checkConnectionStatus() {
XCTAssertEqual(AbstractSocketTest.socket.status, SocketIOClientStatus.Connected)
XCTAssertFalse(AbstractSocketTest.socket.secure)
}
func socketMultipleEmit(testName:String, emitData:Array<AnyObject>, callback:NormalCallback){
let finalTestname = generateTestName(testName)
weak var expection = self.expectationWithDescription(finalTestname)
func didGetEmit(result:NSArray?, ack:AckEmitter?) {
callback(result, ack)
if let expection = expection {
expection.fulfill()
}
}
AbstractSocketTest.socket.emit(finalTestname, withItems: emitData)
AbstractSocketTest.socket.on(finalTestname + "Return", callback: didGetEmit)
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
}
func socketEmit(testName:String, emitData:AnyObject?, callback:NormalCallback){
let finalTestname = generateTestName(testName)
weak var expection = self.expectationWithDescription(finalTestname)
func didGetEmit(result:NSArray?, ack:AckEmitter?) {
callback(result, ack)
if let expection = expection {
expection.fulfill()
}
}
AbstractSocketTest.socket.on(finalTestname + "Return", callback: didGetEmit)
if let emitData = emitData {
AbstractSocketTest.socket.emit(finalTestname, emitData)
} else {
AbstractSocketTest.socket.emit(finalTestname)
}
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
}
func socketAcknwoledgeMultiple(testName:String, Data:Array<AnyObject>, callback:NormalCallback){
let finalTestname = generateTestName(testName)
weak var expection = self.expectationWithDescription(finalTestname)
func didGetResult(result:NSArray?) {
callback(result, nil)
if let expection = expection {
expection.fulfill()
}
}
AbstractSocketTest.socket.emitWithAck(finalTestname, withItems: Data)(timeoutAfter: 5, callback: didGetResult)
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
}
func socketAcknwoledge(testName:String, Data:AnyObject?, callback:NormalCallback){
let finalTestname = generateTestName(testName)
weak var expection = self.expectationWithDescription(finalTestname)
func didGet(result:NSArray?) {
callback(result, nil)
if let expection = expection {
expection.fulfill()
}
}
var ack:OnAckCallback!
if let Data = Data {
ack = AbstractSocketTest.socket.emitWithAck(finalTestname, Data)
} else {
ack = AbstractSocketTest.socket.emitWithAck(finalTestname)
}
ack(timeoutAfter: 20, callback: didGet)
waitForExpectationsWithTimeout(SocketEmitTest.TEST_TIMEOUT, handler: nil)
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>io.socket.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@@ -1,88 +0,0 @@
//
// SocketAcknowledgementTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 27.07.15.
//
//
import XCTest
class SocketAcknowledgementTest: AbstractSocketTest {
override func setUp() {
super.setUp()
testKind = TestKind.Acknowledgement
if AbstractSocketTest.socket == nil {
AbstractSocketTest.socket = SocketIOClient(socketURL: "milkbartube.com:6979", opts: [
"reconnects": true, // default true
"reconnectAttempts": -1, // default -1
"reconnectWait": 5, // default 10
"forcePolling": false,
"forceWebsockets": false,// default false
"path": ""])
openConnection()
}else {
AbstractSocketTest.socket.leaveNamespace()
}
}
func testConnectionStatus() {
super.checkConnectionStatus()
}
func testBasic() {
SocketTestCases.testBasic(socketAcknwoledge)
}
func testNull() {
SocketTestCases.testNull(socketAcknwoledge)
}
func testBinary() {
SocketTestCases.testBinary(socketAcknwoledge)
}
func testArray() {
SocketTestCases.testArray(socketAcknwoledge)
}
func testString() {
SocketTestCases.testString(socketAcknwoledge)
}
func testBool() {
SocketTestCases.testBool(socketAcknwoledge)
}
func testInteger() {
SocketTestCases.testInteger(socketAcknwoledge)
}
func testDouble() {
SocketTestCases.testDouble(socketAcknwoledge)
}
func testJSON() {
SocketTestCases.testJSON(socketAcknwoledge)
}
func testJSONWithBuffer() {
SocketTestCases.testJSONWithBuffer(socketAcknwoledge)
}
func testUnicode() {
SocketTestCases.testUnicode(socketAcknwoledge)
}
func testMultipleItems() {
SocketTestCases.testMultipleItems(socketAcknwoledgeMultiple)
}
func testMultipleWithBuffer() {
SocketTestCases.testMultipleItemsWithBuffer(socketAcknwoledgeMultiple)
}
}
-93
View File
@@ -1,93 +0,0 @@
//
// ConvertedSocketTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 25.07.15.
//
//
import XCTest
import Foundation
class SocketEmitTest: AbstractSocketTest {
override func setUp() {
super.setUp()
testKind = TestKind.Emit
if AbstractSocketTest.socket == nil {
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
"reconnects": true, // default true
"reconnectAttempts": -1, // default -1
"reconnectWait": 5, // default 10
"forcePolling": false,
"forceWebsockets": false,// default false
"path": ""]
)
openConnection()
}else {
AbstractSocketTest.socket.leaveNamespace()
}
}
override func tearDown() {
super.tearDown()
}
func testConnectionStatus() {
super.checkConnectionStatus()
}
func testBasic() {
SocketTestCases.testBasic(socketEmit)
}
func testNull() {
SocketTestCases.testNull(socketEmit)
}
func testBinary() {
SocketTestCases.testBinary(socketEmit)
}
func testArray() {
SocketTestCases.testArray(socketEmit)
}
func testString() {
SocketTestCases.testString(socketEmit)
}
func testBool() {
SocketTestCases.testBool(socketEmit)
}
func testInteger() {
SocketTestCases.testInteger(socketEmit)
}
func testDouble() {
SocketTestCases.testDouble(socketEmit)
}
func testJSON() {
SocketTestCases.testJSON(socketEmit)
}
func testJSONWithBuffer() {
SocketTestCases.testJSONWithBuffer(socketEmit)
}
func testUnicode() {
SocketTestCases.testUnicode(socketEmit)
}
func testMultipleItems() {
SocketTestCases.testMultipleItems(socketMultipleEmit)
}
func testMultipleWithBuffer() {
SocketTestCases.testMultipleItemsWithBuffer(socketMultipleEmit)
}
}
@@ -1,88 +0,0 @@
//
// SocketNamespaceAcknowledgementTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 28.07.15.
//
//
import XCTest
class SocketNamespaceAcknowledgementTest: AbstractSocketTest {
override func setUp() {
super.setUp()
testKind = TestKind.Acknowledgement
if AbstractSocketTest.socket == nil {
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
"reconnects": true, // default true
"reconnectAttempts": -1, // default -1
"reconnectWait": 5, // default 10
"forcePolling": false,
"forceWebsockets": false,// default false
"path": "",
"nsp": "/swift"])
openConnection()
}else {
AbstractSocketTest.socket.joinNamespace("/swift")
}
}
func testConnectionStatus() {
super.checkConnectionStatus()
}
func testBasic() {
SocketTestCases.testBasic(socketAcknwoledge)
}
func testNull() {
SocketTestCases.testNull(socketAcknwoledge)
}
func testBinary() {
SocketTestCases.testBinary(socketAcknwoledge)
}
func testArray() {
SocketTestCases.testArray(socketAcknwoledge)
}
func testString() {
SocketTestCases.testString(socketAcknwoledge)
}
func testBool() {
SocketTestCases.testBool(socketAcknwoledge)
}
func testInteger() {
SocketTestCases.testInteger(socketAcknwoledge)
}
func testDouble() {
SocketTestCases.testDouble(socketAcknwoledge)
}
func testJSON() {
SocketTestCases.testJSON(socketAcknwoledge)
}
func testJSONWithBuffer() {
SocketTestCases.testJSONWithBuffer(socketAcknwoledge)
}
func testUnicode() {
SocketTestCases.testUnicode(socketAcknwoledge)
}
func testMultipleItems() {
SocketTestCases.testMultipleItems(socketAcknwoledgeMultiple)
}
func testMultipleWithBuffer() {
SocketTestCases.testMultipleItemsWithBuffer(socketAcknwoledgeMultiple)
}
}
@@ -1,87 +0,0 @@
//
// SocketNamespaceEmitTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 26.07.15.
//
//
import XCTest
class SocketNamespaceEmitTest: AbstractSocketTest {
override func setUp() {
super.setUp()
testKind = TestKind.Emit
if AbstractSocketTest.socket == nil {
AbstractSocketTest.socket = SocketIOClient(socketURL: AbstractSocketTest.serverURL, opts: [
"reconnects": true, // default true
"reconnectAttempts": -1, // default -1
"reconnectWait": 5, // default 10
"forcePolling": false,
"forceWebsockets": false,// default false
"path": "",
"nsp": "/swift"])
openConnection()
}else {
AbstractSocketTest.socket.joinNamespace("/swift")
}
}
func testConnectionStatus() {
super.checkConnectionStatus()
}
func testBasic() {
SocketTestCases.testBasic(socketEmit)
}
func testNull() {
SocketTestCases.testNull(socketEmit)
}
func testBinary() {
SocketTestCases.testBinary(socketEmit)
}
func testArray() {
SocketTestCases.testArray(socketEmit)
}
func testString() {
SocketTestCases.testString(socketEmit)
}
func testBool() {
SocketTestCases.testBool(socketEmit)
}
func testInteger() {
SocketTestCases.testInteger(socketEmit)
}
func testDouble() {
SocketTestCases.testDouble(socketEmit)
}
func testJSON() {
SocketTestCases.testJSON(socketEmit)
}
func testJSONWithBuffer() {
SocketTestCases.testJSONWithBuffer(socketEmit)
}
func testUnicode() {
SocketTestCases.testUnicode(socketEmit)
}
func testMultipleItems() {
SocketTestCases.testMultipleItems(socketMultipleEmit)
}
func testMultipleWithBuffer() {
SocketTestCases.testMultipleItemsWithBuffer(socketMultipleEmit)
}
}
-248
View File
@@ -1,248 +0,0 @@
//
// SocketTestCases.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 02.08.15.
//
//
import XCTest
import Foundation
class SocketTestCases: NSObject {
typealias SocketSendFunction = (testName:String, emitData:AnyObject?, callback:NormalCallback)->()
static func testBasic(abstractSocketSend:SocketSendFunction) {
let testName = "basicTest"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
}
abstractSocketSend(testName: testName, emitData: nil, callback: didGetResult)
}
static func testNull(abstractSocketSend:SocketSendFunction) {
let testName = "testNull"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let _ = result?.firstObject as? NSNull {
}else
{
XCTFail("Should have NSNull as result")
}
}
abstractSocketSend(testName: testName, emitData: NSNull(), callback: didGetResult)
}
static func testBinary(abstractSocketSend:SocketSendFunction) {
let testName = "testBinary"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let data = result?.firstObject as? NSData {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
XCTAssertEqual(string, "gakgakgak2")
}else {
XCTFail("Should have NSData as result")
}
}
let data = NSString(string: "gakgakgak2").dataUsingEncoding(NSUTF8StringEncoding)!
abstractSocketSend(testName: testName, emitData: data, callback: didGetResult)
}
static func testArray(abstractSocketSend:SocketSendFunction) {
let testName = "testArray"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let array = result?.firstObject as? NSArray {
XCTAssertEqual(array.count, 2)
XCTAssertEqual((array.firstObject! as! String), "test3")
XCTAssertEqual((array.lastObject! as! String), "test4")
}else {
XCTFail("Should have NSArray as result")
}
}
abstractSocketSend(testName: testName, emitData: ["test1", "test2"], callback: didGetResult)
}
static func testString(abstractSocketSend:SocketSendFunction) {
let testName = "testString"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let string = result?.firstObject as? String {
XCTAssertEqual(string, "polo")
}else {
XCTFail("Should have String as result")
}
}
abstractSocketSend(testName: testName, emitData: "marco", callback: didGetResult)
}
static func testBool(abstractSocketSend:SocketSendFunction) {
let testName = "testBool"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let bool = result?.firstObject as? NSNumber {
XCTAssertTrue(bool.boolValue)
}else {
XCTFail("Should have Boolean as result")
}
}
abstractSocketSend(testName: testName, emitData: false, callback: didGetResult)
}
static func testInteger(abstractSocketSend:SocketSendFunction) {
let testName = "testInteger"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let integer = result?.firstObject as? Int {
XCTAssertEqual(integer, 20)
}else {
XCTFail("Should have Integer as result")
}
}
abstractSocketSend(testName: testName, emitData: 10, callback: didGetResult)
}
static func testDouble(abstractSocketSend:SocketSendFunction) {
let testName = "testDouble"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let double = result?.firstObject as? NSNumber {
XCTAssertEqual(double.floatValue, 1.2)
}else {
XCTFail("Should have Double as result")
}
}
abstractSocketSend(testName: testName, emitData: 1.1, callback: didGetResult)
}
static func testJSONWithBuffer(abstractSocketSend:SocketSendFunction) {
let testName = "testJSONWithBuffer"
let data = "0".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let json = result?.firstObject as? NSDictionary {
XCTAssertEqual((json.valueForKey("testString")! as! String), "test")
XCTAssertEqual((json.valueForKey("testNumber")! as! Int), 15)
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).count, 2)
XCTAssertEqual(((json.valueForKey("testArray")! as! Array<AnyObject>).last! as! Int), 1)
let string = NSString(data: (json.valueForKey("testArray")! as! Array<AnyObject>).first! as! NSData, encoding: NSUTF8StringEncoding)!
XCTAssertEqual(string, "gakgakgak2")
}else {
XCTFail("Should have NSDictionary as result")
}
}
let json = ["name": "test", "testArray": ["hallo"], "nestedTest": ["test": "test"], "number": 15, "buf": data]
abstractSocketSend(testName: testName, emitData: json, callback: didGetResult)
}
static func testJSON(abstractSocketSend:SocketSendFunction) {
let testName = "testJSON"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let json = result?.firstObject as? NSDictionary {
XCTAssertEqual((json.valueForKey("testString")! as! String), "test")
XCTAssertEqual(json.valueForKey("testNumber")! as? Int, 15)
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).count, 2)
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).first! as? Int, 1)
XCTAssertEqual((json.valueForKey("testArray")! as! Array<AnyObject>).last! as? Int, 1)
}else {
XCTFail("Should have NSDictionary as result")
}
}
let json = ["name": "test", "testArray": ["hallo"], "nestedTest": ["test": "test"], "number": 15]
abstractSocketSend(testName: testName, emitData: json, callback: didGetResult)
}
static func testUnicode(abstractSocketSend:SocketSendFunction) {
let testName = "testUnicode"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
if let unicode = result?.firstObject as? String {
XCTAssertEqual(unicode, "🚄")
}else {
XCTFail("Should have String as result")
}
}
abstractSocketSend(testName: testName, emitData: "🚀", callback: didGetResult)
}
static func testMultipleItemsWithBuffer(abstractSocketMultipleSend:(testName:String, emitData:Array<AnyObject>, callback:NormalCallback)->()) {
let testName = "testMultipleItemsWithBuffer"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
XCTAssertEqual(result!.count, 5)
if result!.count != 5 {
XCTFail("Fatal Fail. Lost some Data")
return
}
if let array = result?.firstObject as? Array<AnyObject> {
XCTAssertEqual((array.last! as! Int), 2)
XCTAssertEqual((array.first! as! Int), 1)
}else {
XCTFail("Should have Array as result")
}
if let dict = result?[1] as? NSDictionary {
XCTAssertEqual((dict.valueForKey("test") as! String), "bob")
}else {
XCTFail("Should have NSDictionary as result")
}
if let number = result?[2] as? Int {
XCTAssertEqual(number, 25)
}else {
XCTFail("Should have Integer as result")
}
if let string = result?[3] as? String {
XCTAssertEqual(string, "polo")
}else {
XCTFail("Should have Integer as result")
}
if let data = result?[4] as? NSData {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
XCTAssertEqual(string, "gakgakgak2")
}else {
XCTFail("Should have NSData as result")
}
}
let data = NSString(string: "gakgakgak2").dataUsingEncoding(NSUTF8StringEncoding)!
let emitArray = [["test1", "test2"], ["test": "test"], 15, "marco", data]
abstractSocketMultipleSend(testName: testName, emitData: emitArray, callback: didGetResult)
}
static func testMultipleItems(abstractSocketMultipleSend:(testName:String, emitData:Array<AnyObject>, callback:NormalCallback)->()) {
let testName = "testMultipleItems"
func didGetResult(result:NSArray?, ack:AckEmitter?) {
XCTAssertEqual(result!.count, 5)
if result!.count != 5 {
XCTFail("Fatal Fail. Lost some Data")
return
}
if let array = result?.firstObject as? Array<AnyObject> {
XCTAssertEqual((array.last! as! Int), 2)
XCTAssertEqual((array.first! as! Int), 1)
}else {
XCTFail("Should have Array as result")
}
if let dict = result?[1] as? NSDictionary {
XCTAssertEqual((dict.valueForKey("test") as! String), "bob")
}else {
XCTFail("Should have NSDictionary as result")
}
if let number = result?[2] as? Int {
XCTAssertEqual(number, 25)
}else {
XCTFail("Should have Integer as result")
}
if let string = result?[3] as? String {
XCTAssertEqual(string, "polo")
}else {
XCTFail("Should have Integer as result")
}
if let bool = result?[4] as? NSNumber {
XCTAssertFalse(bool.boolValue)
}else {
XCTFail("Should have NSNumber as result")
}
}
let emitArray = [["test1", "test2"], ["test": "test"], 15, "marco", false]
abstractSocketMultipleSend(testName: testName, emitData: emitArray, callback: didGetResult)
}
}
-13
View File
@@ -1,13 +0,0 @@
//
// TestKind.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 28.07.15.
//
//
import Foundation
enum TestKind: String {
case Emit, Acknowledgement
}
-704
View File
@@ -1,704 +0,0 @@
//
// 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, WebSocketDelegate {
private typealias Probe = (msg: String, type: PacketType, data: [NSData]?)
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketEngine"
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let session: NSURLSession!
private let workQueue = NSOperationQueue()
private var closed = false
private var extraHeaders: [String: String]?
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingInterval: Double?
private var pingTimer: NSTimer?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var websocketConnected = false
private(set) var connected = false
private(set) var polling = true
private(set) var websocket = false
weak var client: SocketEngineClient?
var cookies: [NSHTTPCookie]?
var sid = ""
var socketPath = ""
var urlPolling: String?
var urlWebSocket: String?
var ws: WebSocket?
@objc public enum PacketType: Int {
case Open, Close, Ping, Pong, Message, Upgrade, Noop
init?(str: String) {
if let value = Int(str), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client: SocketEngineClient, sessionDelegate: NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: workQueue)
}
public convenience init(client: SocketEngineClient, opts: NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
forcePolling = opts?["forcePolling"] as? Bool ?? false
cookies = opts?["cookies"] as? [NSHTTPCookie]
socketPath = opts?["path"] as? String ?? ""
extraHeaders = opts?["extraHeaders"] as? [String: String]
}
deinit {
Logger.log("Engine is being deinit", type: logType)
}
private func checkIfMessageIsBase64Binary(var message: String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: message.startIndex.advancedBy(2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
client?.parseBinaryData(data)
}
}
}
public func close(fast fast: Bool) {
Logger.log("Engine is being closed. Fast: %@", type: logType, args: fast)
pingTimer?.invalidate()
closed = true
ws?.disconnect()
if fast || polling {
write("", withType: PacketType.Close, withData: nil)
client?.engineDidClose("Disconnect")
}
stopPolling()
}
private func createBinaryDataForSend(data: NSData) -> (NSData?, String?) {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
let 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 client == nil {
return (nil, nil)
}
let path = socketPath == "" ? "/socket.io" : socketPath
let url = "\(client!.socketURL)\(path)/?transport="
var urlPolling: String
var urlWebSocket: String
if client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
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) {
let wsUrl = urlWebSocket! + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!,
cookies: cookies)
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.queue = handleQueue
ws?.delegate = self
if connect {
ws?.connect()
}
}
private func doFastUpgrade() {
if waitingForPoll {
Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: PacketType.Upgrade, datas: nil)
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func doPoll() {
if websocket || waitingForPoll || !connected {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(req)
}
private func doRequest(req: NSMutableURLRequest) {
if !polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
Logger.log("Doing polling request", type: logType)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil || data == nil {
if this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
} else {
Logger.error(err?.localizedDescription ?? "Error", type: this.logType)
}
return
}
Logger.log("Got polling response", type: this.logType)
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(this.parseQueue) {[weak this] in
this?.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}}.resume()
}
private func flushProbeWait() {
Logger.log("Flushing probe wait", type: logType)
dispatch_async(emitQueue) {[weak self] in
if let this = self {
for waiter in this.probeWait {
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
this.probeWait.removeAll(keepCapacity: false)
if this.postWait.count != 0 {
this.flushWaitingForPostToWebSocket()
}
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in postWait {
let len = packet.characters.count
postStr += "\(len):\(packet)"
}
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)")!)
if let cookies = cookies {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(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")
waitingForPost = true
Logger.log("POSTing: %@", type: logType, args: postStr)
session.dataTaskWithRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil && this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
return
} else if err != nil {
NSLog(err?.localizedDescription ?? "Error")
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {[weak this] in
if !(this?.fastUpgrade ?? true) {
this?.flushWaitingForPost()
this?.doPoll()
}
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else {return}
for msg in postWait {
ws.writeString(msg)
}
postWait.removeAll(keepCapacity: true)
}
private func handleClose() {
if let client = client where polling == true {
client.engineDidClose("Disconnect")
}
}
private func handleMessage(message: String) {
client?.parseSocketMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let sid = json?["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json?["upgrades"] as? [String] {
upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0
} else {
upgradeWs = false
}
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocket(andConnect: true)
}
}
} catch {
Logger.error("Error parsing open packet", type: logType)
return
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
}
private func handlePong(pongMessage: String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason: String) {
connected = false
ws?.disconnect()
pingTimer?.invalidate()
waitingForPoll = false
waitingForPost = false
if !closed {
client?.didError(reason)
client?.engineDidClose(reason)
}
}
public func open(opts: [String: AnyObject]? = nil) {
if connected {
Logger.error("Tried to open while connected", type: logType)
client?.didError("Tried to open while connected")
return
}
Logger.log("Starting engine", type: logType)
Logger.log("Handshaking", type: logType)
closed = false
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
polling = false
websocket = true
createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doRequest(reqPolling)
}
private func parsePollingMessage(str: String) {
guard str.characters.count != 1 else {
return
}
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilStringOccurence(":")) {
let str = reader.read(n)
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
} else {
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
break
}
}
}
private func parseEngineData(data: NSData) {
Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
private func parseEngineMessage(var message: String, fromPolling: Bool) {
Logger.log("Got message: %@", type: logType, args: message)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1]) ?? "") ?? {
self.checkIfMessageIsBase64Binary(message)
return .Noop
}()
switch type {
case PacketType.Message:
message.removeAtIndex(message.startIndex)
handleMessage(message)
case PacketType.Noop:
handleNOOP()
case PacketType.Pong:
handlePong(message)
case PacketType.Open:
message.removeAtIndex(message.startIndex)
handleOpen(message)
case PacketType.Close:
handleClose()
default:
Logger.log("Got unknown packet type", type: logType)
}
}
private func probeWebSocket() {
if websocketConnected {
sendWebSocketMessage("probe", withType: PacketType.Ping)
}
}
/// Send an engine message (4)
public func send(msg: String, withData datas: [NSData]?) {
if probing {
probeWait.append((msg, PacketType.Message, datas))
} else {
write(msg, withType: PacketType.Message, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: PacketType.Ping, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg: String, withType type: PacketType,
datas:[NSData]? = nil) {
Logger.log("Sending poll: %@ as type: %@", type: logType, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
postWait.append(strMsg)
for data in datas ?? [] {
let (_, b64Data) = createBinaryDataForSend(data)
postWait.append(b64Data!)
}
if !waitingForPost {
flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str: String, withType type: PacketType,
datas:[NSData]? = nil) {
Logger.log("Sending ws: %@ as type: %@", type: logType, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas ?? [] {
let (data, _) = createBinaryDataForSend(data)
if data != nil {
ws?.writeData(data!)
}
}
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
func stopPolling() {
session.invalidateAndCancel()
}
private func upgradeTransport() {
if websocketConnected {
Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: PacketType.Noop)
// After this point, we should not send anymore polling messages
}
}
/**
Write a message, independent of transport.
*/
public func write(msg: String, withType type: PacketType, withData data: [NSData]?) {
dispatch_async(emitQueue) {
if self.connected {
if self.websocket {
Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendPollMessage(msg, withType: type, datas: data)
}
}
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
websocketConnected = true
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
websocketConnected = false
probing = false
if closed {
client?.engineDidClose("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
client?.didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
parseEngineData(data)
}
}
-504
View File
@@ -1,504 +0,0 @@
//
// 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 {
private let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue: dispatch_queue_t!
public let socketURL: String
public private(set) var engine: SocketEngine?
public private(set) var secure = false
public private(set) var status = SocketIOClientStatus.NotConnected
public var nsp = "/"
public var opts: [String: AnyObject]?
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
}
private let logType = "SocketIOClient"
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = ContiguousArray<SocketEventHandler>()
private var connectParams: [String: AnyObject]?
private var reconnectTimer: NSTimer?
private let reconnectAttempts: Int!
private var ackHandlers = SocketAckManager()
private var currentAck = -1
var waitingData = [SocketPacket]()
/**
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
if let connectParams = opts?["connectParams"] as? [String: AnyObject] {
self.connectParams = connectParams
}
if let logger = opts?["logger"] as? SocketLogger {
Logger = logger
}
if let log = opts?["log"] as? Bool {
Logger.log = log
}
if let nsp = opts?["nsp"] as? String {
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)
}
if let handleQueue = opts?["handleQueue"] as? dispatch_queue_t {
self.handleQueue = handleQueue
} else {
self.handleQueue = dispatch_get_main_queue()
}
super.init()
}
deinit {
Logger.log("Client is being deinit", type: logType)
engine?.close(fast: true)
}
private func addEngine() -> SocketEngine {
Logger.log("Adding engine", type: logType)
let newEngine = SocketEngine(client: self, opts: opts)
engine = newEngine
return newEngine
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
/**
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 fast: Bool) {
Logger.log("Closing socket", type: logType)
reconnects = false
status = SocketIOClientStatus.Closed
engine?.close(fast: fast)
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter:Int,
withTimeoutHandler handler:(() -> Void)?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard status != .Connected else {
return
}
if status == .Closed {
Logger.log("Warning! This socket was previously closed. This might be dangerous!",
type: logType)
}
status = SocketIOClientStatus.Connecting
addEngine().open(connectParams)
guard timeoutAfter != 0 else {
return
}
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
if self.status != .Connected {
self.status = .Closed
self.engine?.close(fast: true)
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(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()) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
handleEvent("connect", data: nil, isInternalMessage: false)
}
func didDisconnect(reason: String) {
guard status != .Closed else {
return
}
Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close(fast: true)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason: AnyObject) {
Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect(fast fast: Bool) {
close(fast: fast)
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
return
}
dispatch_async(emitQueue) {
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 {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
Logger.log("Emitting: %@", type: logType, args: str)
if packet.type == .BinaryEvent {
engine?.send(str, withData: packet.binary)
} else {
engine?.send(str, withData: nil)
}
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
Logger.log("Emitting Ack: %@", type: self.logType, args: str)
if packet.type == SocketPacket.PacketType.BinaryAck {
self.engine?.send(str, withData: packet.binary)
} else {
self.engine?.send(str, withData: nil)
}
}
}
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: AnyObject?) {
Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
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,
wantsAck ack: Int? = nil) {
guard status == .Connected || isInternalMessage else {
return
}
Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
if anyHandler != nil {
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
}
}
for handler in handlers where handler.event == event {
if let ack = ack {
dispatch_async(handleQueue) {
handler.executeCallback(data, withAck: ack, withSocket: self)
}
} else {
dispatch_async(handleQueue) {
handler.executeCallback(data)
}
}
}
}
/**
Leaves nsp and goes back to /
*/
public func leaveNamespace() {
if nsp != "/" {
engine?.send("1\(nsp)", withData: nil)
nsp = "/"
}
}
/**
Joins nsp if it is not /
*/
public func joinNamespace() {
Logger.log("Joining namespace", type: logType)
if nsp != "/" {
engine?.send("0\(nsp)", withData: nil)
}
}
/**
Joins namespace /
*/
public func joinNamespace(namespace: String) {
self.nsp = namespace
joinNamespace()
}
/**
Removes handler(s)
*/
public func off(event: String) {
Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = ContiguousArray(handlers.filter { $0.event != event })
}
/**
Adds a handler for an event.
*/
public func on(event: String, callback: NormalCallback) {
Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, callback: callback)
handlers.append(handler)
}
/**
Adds a handler for an event.
*/
public func onObjectiveC(event: String, callback: NormalCallbackObjectiveC) {
Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, callback: callback)
handlers.append(handler)
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
public func open() {
connect()
}
public func parseSocketMessage(msg: String) {
dispatch_async(handleQueue) {
SocketParser.parseSocketMessage(msg, socket: self)
}
}
public func parseBinaryData(data: NSData) {
dispatch_async(handleQueue) {
SocketParser.parseBinaryData(data, socket: self)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
engine?.stopPolling()
tryReconnect()
}
private func tryReconnect() {
if reconnectTimer == nil {
Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt++
connect()
}
}
-175
View File
@@ -1,175 +0,0 @@
//
// SocketParser.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
class SocketParser {
private static func isCorrectNamespace(nsp: String, _ socket: SocketIOClient) -> Bool {
return nsp == socket.nsp
}
private static func handleEvent(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.handleEvent(p.event, data: p.args,
isInternalMessage: false, wantsAck: p.id)
}
private static func handleAck(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.handleAck(p.id, data: p.data)
}
private static func handleBinary(p: SocketPacket, socket: SocketIOClient) {
guard isCorrectNamespace(p.nsp, socket) else { return }
socket.waitingData.append(p)
}
private static func handleConnect(p: SocketPacket, socket: SocketIOClient) {
if p.nsp == "/" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "/" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
}
static func parseString(message: String) -> SocketPacket? {
var parser = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(str: parser.read(1))
else {return nil}
if !parser.hasNext {
return SocketPacket(type: type, nsp: "/")
}
var namespace: String?
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return nil
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
}
if !parser.hasNext {
return SocketPacket(type: type, id: -1,
nsp: namespace ?? "/", placeholders: placeholders)
}
var idString = ""
while parser.hasNext {
if let int = Int(parser.read(1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
break
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
return SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders)
}
// Parses data for events
static func parseData(data: String) -> AnyObject? {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
return try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers)
} catch {
Logger.error("Parsing JSON: %@", type: "SocketParser", args: data)
return nil
}
}
// Parses messages recieved
static func parseSocketMessage(message: String, socket: SocketIOClient) {
guard !message.isEmpty else { return }
Logger.log("Parsing %@", type: "SocketParser", args: message)
guard let pack = parseString(message) else {
Logger.error("Parsing message: %@", type: "SocketParser", args: message)
return
}
Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
switch pack.type {
case .Event:
handleEvent(pack, socket: socket)
case .Ack:
handleAck(pack, socket: socket)
case .BinaryEvent:
handleBinary(pack, socket: socket)
case .BinaryAck:
handleBinary(pack, socket: socket)
case .Connect:
handleConnect(pack, socket: socket)
case .Disconnect:
socket.didDisconnect("Got Disconnect")
case .Error:
socket.didError("Error: \(pack.data)")
}
}
static func parseBinaryData(data: NSData, socket: SocketIOClient) {
guard !socket.waitingData.isEmpty else {
Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
let shouldExecute = socket.waitingData[socket.waitingData.count - 1].addData(data)
guard shouldExecute else {
return
}
var packet = socket.waitingData.removeLast()
packet.fillInPlaceholders()
if packet.type != .BinaryAck {
socket.handleEvent(packet.event, data: packet.args,
isInternalMessage: false, wantsAck: packet.id)
} else {
socket.handleAck(packet.id, data: packet.args)
}
}
}
+47
View File
@@ -0,0 +1,47 @@
//
// SocketAckEmitter.swift
// Socket.IO-Client-Swift
//
// 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
// 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 SocketAckEmitter: NSObject {
let socket: SocketIOClient
let ackNum: Int
init(socket: SocketIOClient, ackNum: Int) {
self.socket = socket
self.ackNum = ackNum
}
public func with(items: AnyObject...) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, withItems: items)
}
public func with(items: [AnyObject]) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, withItems: items)
}
}
@@ -56,7 +56,7 @@ struct SocketAckManager {
acks.insert(SocketAck(ack: ack, callback: callback))
}
mutating func executeAck(ack: Int, items: [AnyObject]?) {
mutating func executeAck(ack: Int, items: [AnyObject]) {
let callback = acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
File renamed without changes.
+43
View File
@@ -0,0 +1,43 @@
//
// SocketClientSpec.swift
// Socket.IO-Client-Swift
//
// 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
// 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.
protocol SocketClientSpec: class {
var nsp: String { get set }
var waitingData: [SocketPacket] { get set }
func didConnect()
func didDisconnect(reason: String)
func didError(reason: String)
func handleAck(ack: Int, data: [AnyObject])
func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int)
func joinNamespace(namespace: String)
}
extension SocketClientSpec {
func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: "SocketIOClient", args: reason)
handleEvent("error", data: [reason], isInternalMessage: true, withAck: -1)
}
}
+561
View File
@@ -0,0 +1,561 @@
//
// 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, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
public var postWait = [String]()
public var waitingForPoll = false
public var waitingForPost = false
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var 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 pingTimer: NSTimer?
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: NSURLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io"
public private(set) var urlPolling = ""
public private(set) var urlWebSocket = ""
public private(set) var websocket = false
public private(set) var ws: WebSocket?
public weak var client: SocketEngineClient?
private weak var sessionDelegate: NSURLSessionDelegate?
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData])
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let logType = "SocketEngine"
private let url: String
private var connectParams: [String: AnyObject]?
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 selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) {
self.client = client
self.url = url
for option in options {
switch option {
case let .SessionDelegate(delegate):
sessionDelegate = delegate
case let .ForcePolling(force):
forcePolling = force
case let .ForceWebsockets(force):
forceWebsockets = force
case let .Cookies(cookies):
self.cookies = cookies
case let .Path(path):
socketPath = path
case let .ExtraHeaders(headers):
extraHeaders = headers
case let .VoipEnabled(enable):
voipEnabled = enable
case let .Secure(secure):
self.secure = secure
case let .SelfSigned(selfSigned):
self.selfSigned = selfSigned
default:
continue
}
}
}
public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) {
self.init(client: client, url: url,
options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType)
closed = true
stopPolling()
}
private func checkAndHandleEngineError(msg: String) {
guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false) else { return }
do {
if let dict = try NSJSONSerialization.JSONObjectWithData(stringData,
options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
guard let code = dict["code"] as? Int else { return }
guard let error = dict["message"] as? String else { return }
switch code {
case 0: // Unknown transport
didError(error)
case 1: // Unknown sid. clear and retry connect
didError(error)
case 2: // Bad handshake request
didError(error)
case 3: // Bad request
didError(error)
default:
didError(error)
}
}
} catch {
didError("Got unknown error from server \(msg)")
}
}
private func checkIfMessageIsBase64Binary(message: String) -> Bool {
if message.hasPrefix("b4") {
// binary in base64 string
let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex]
if let data = NSData(base64EncodedString: noPrefix,
options: .IgnoreUnknownCharacters) {
client?.parseEngineBinaryData(data)
}
return true
} else {
return false
}
}
public func close(reason: String) {
func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) {
sid = ""
closed = true
invalidated = true
connected = false
pingTimer?.invalidate()
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason)
}
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if websocket {
sendWebSocketMessage("", withType: .Close, withData: [])
postSendClose(nil, nil, nil)
} else {
// We need to take special care when we're polling that we send it ASAP
postWait.append(String(SocketEnginePacketType.Close.rawValue))
let req = createRequestForPostWithPostWait()
doRequest(req, withCallback: postSendClose)
}
}
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
if client == nil {
return ("", "")
}
let socketURL = "\(url)\(socketPath)/?transport="
var urlPolling: String
var urlWebSocket: String
if secure {
urlPolling = "https://" + socketURL + "polling"
urlWebSocket = "wss://" + socketURL + "websocket"
} else {
urlPolling = "http://" + socketURL + "polling"
urlWebSocket = "ws://" + socketURL + "websocket"
}
if params != nil {
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 createWebsocketAndConnect() {
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.queue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
ws?.selfSignedSSL = selfSigned
ws?.connect()
}
public func didError(error: String) {
DefaultSocketLogger.Logger.error(error, type: logType)
client?.engineDidError(error)
close(error)
}
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)
dispatch_async(emitQueue) {
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()
}
}
}
// We had packets waiting for send when we upgraded
// Send them raw
public func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else { return }
for msg in postWait {
ws.writeString(fixDoubleUTF8(msg))
}
postWait.removeAll(keepCapacity: true)
}
private func handleClose(reason: String) {
client?.engineDidClose(reason)
}
private func handleMessage(message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let sid = json?["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json?["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen?("Connect")
}
} catch {
didError("Error parsing open packet")
return
}
}
private func handlePong(pongMessage: String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
public func open(opts: [String: AnyObject]?) {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. This is probably a programming error. "
+ "Abandoning open attempt", type: logType)
return
}
connectParams = opts
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
public func parseEngineData(data: NSData) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
public func parseEngineMessage(message: String, fromPolling: Bool) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let reader = SocketStringReader(message: message)
let fixedString: String
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
if !checkIfMessageIsBase64Binary(message) {
checkAndHandleEngineError(message)
}
return
}
if fromPolling && type != .Noop {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
}
switch type {
case .Message:
handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Noop:
handleNOOP()
case .Pong:
handlePong(fixedString)
case .Open:
handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex])
case .Close:
handleClose(fixedString)
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
private func resetEngine() {
closed = false
connected = false
fastUpgrade = false
polling = true
probing = false
invalidated = false
session = NSURLSession(configuration: .defaultSessionConfiguration(),
delegate: sessionDelegate,
delegateQueue: NSOperationQueue())
sid = ""
waitingForPoll = false
waitingForPost = false
websocket = false
}
/// Send an engine message (4)
public func send(msg: String, withData datas: [NSData]) {
if probing {
probeWait.append((msg, .Message, datas))
} else {
write(msg, withType: .Message, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
pongsMissed += 1
write("", withType: .Ping, withData: [])
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
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: [NSData]) {
dispatch_async(emitQueue) {
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 {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendPollMessage(msg, withType: type, withData: 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("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
}
@@ -25,12 +25,10 @@
import Foundation
@objc public protocol SocketEngineClient {
var socketURL: String {get}
var secure: Bool {get}
func didError(reason: AnyObject)
@objc public protocol SocketEngineClient {
func engineDidError(reason: String)
func engineDidClose(reason: String)
func parseSocketMessage(msg: String)
func parseBinaryData(data: NSData)
optional func engineDidOpen(reason: String)
func parseEngineMessage(msg: String)
func parseEngineBinaryData(data: NSData)
}
@@ -1,8 +1,8 @@
//
// SocketFixUTF8.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
}
+231
View File
@@ -0,0 +1,231 @@
//
// 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: NSURLSession? { 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: [NSData])
func stopPolling()
}
// Default polling methods
extension SocketEnginePollable {
private func addHeaders(req: NSMutableURLRequest) {
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
}
func createRequestForPostWithPostWait() -> NSURLRequest {
var postStr = ""
for packet in postWait {
let len = packet.characters.count
postStr += "\(len):\(packet)"
}
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
addHeaders(req)
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")
return req
}
public func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
addHeaders(req)
doLongPoll(req)
}
func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
if !polling || closed || invalidated {
DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling")
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTaskWithRequest(req, completionHandler: callback).resume()
}
func doLongPoll(req: NSURLRequest) {
doRequest(req) {[weak self] data, res, err in
guard let this = self else {return}
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(err?.localizedDescription ?? "Error")
}
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: NSUTF8StringEncoding) {
dispatch_async(this.parseQueue) {
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(req) {[weak self] data, res, err in
guard let this = self else { return }
if err != nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(err?.localizedDescription ?? "Error")
}
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {
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.readUntilStringOccurence(":")) {
let str = reader.read(n)
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
} else {
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
break
}
}
}
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage = doubleEncodeUTF8(message)
let strMsg = "\(type.rawValue)\(fixedMessage)"
postWait.append(strMsg)
for data in datas {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
public func stopPolling() {
waitingForPoll = false
waitingForPost = false
session?.finishTasksAndInvalidate()
}
}
+77
View File
@@ -0,0 +1,77 @@
//
// 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 cookies: [NSHTTPCookie]? { get }
var extraHeaders: [String: String]? { get }
var fastUpgrade: Bool { get }
var forcePolling: Bool { get }
var forceWebsockets: Bool { get }
var parseQueue: dispatch_queue_t! { get }
var pingTimer: NSTimer? { get }
var polling: Bool { get }
var probing: Bool { get }
var emitQueue: dispatch_queue_t! { get }
var handleQueue: dispatch_queue_t! { get }
var sid: String { get }
var socketPath: String { get }
var urlPolling: String { get }
var urlWebSocket: String { get }
var websocket: Bool { get }
init(client: SocketEngineClient, url: String, options: NSDictionary?)
func close(reason: String)
func didError(error: String)
func doFastUpgrade()
func flushWaitingForPostToWebSocket()
func open(opts: [String: AnyObject]?)
func parseEngineData(data: NSData)
func parseEngineMessage(message: String, fromPolling: Bool)
func send(msg: String, withData datas: [NSData])
func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData])
}
extension SocketEngineSpec {
func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x4)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return .Left(mutData)
} else {
let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return .Right(str)
}
}
}
+64
View File
@@ -0,0 +1,64 @@
//
// 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 {
var ws: WebSocket? { get }
func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType, withData datas: [NSData])
}
// 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: [NSData]) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: "SocketEngine", args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas {
if case let .Left(bin) = createBinaryDataForSend(data) {
ws?.writeData(bin)
}
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
parseEngineData(data)
}
}
@@ -24,37 +24,12 @@
import Foundation
private func emitAckCallback(socket: SocketIOClient?, num: Int?)
(items: AnyObject...) -> Void {
socket?.emitAck(num ?? -1, withItems: items)
}
private func emitAckCallbackObjectiveC(socket: SocketIOClient?, num: Int?)
(items: NSArray) -> Void {
socket?.emitAck(num ?? -1, withItems: items as [AnyObject])
}
struct SocketEventHandler {
let event: String
let callback: NormalCallback?
let callBackObjectiveC: NormalCallbackObjectiveC?
let id: NSUUID
let callback: NormalCallback
init(event: String, callback: NormalCallback) {
self.event = event
self.callback = callback
self.callBackObjectiveC = nil
}
init(event: String, callback: NormalCallbackObjectiveC) {
self.event = event
self.callback = nil
self.callBackObjectiveC = callback
}
func executeCallback(items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
self.callback != nil ?
self.callback?(items, emitAckCallback(socket, num: ack))
: self.callBackObjectiveC?(items, emitAckCallbackObjectiveC(socket, num: ack))
func executeCallback(items: [AnyObject], withAck ack: Int, withSocket socket: SocketIOClient) {
callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
}
}
+44
View File
@@ -0,0 +1,44 @@
//
// SocketFixUTF8.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/16/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
func fixDoubleUTF8(string: String) -> String {
if let utf8 = string.dataUsingEncoding(NSISOLatin1StringEncoding),
latin1 = NSString(data: utf8, encoding: NSUTF8StringEncoding) {
return latin1 as String
} else {
return string
}
}
func doubleEncodeUTF8(string: String) -> String {
if let latin1 = string.dataUsingEncoding(NSUTF8StringEncoding),
utf8 = NSString(data: latin1, encoding: NSISOLatin1StringEncoding) {
return utf8 as String
} else {
return string
}
}
+514
View File
@@ -0,0 +1,514 @@
//
// 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: String
public private(set) var engine: SocketEngineSpec?
public private(set) var status = SocketIOClientStatus.NotConnected
public var connectParams: [String: AnyObject]?
public var forceNew = false
public var nsp = "/"
public var options: Set<SocketIOClientOption>
public var reconnects = true
public var reconnectWait = 10
public var sid: String? {
return engine?.sid
}
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketIOClient"
private let parseQueue = dispatch_queue_create("com.socketio.parseQueue", DISPATCH_QUEUE_SERIAL)
private var anyHandler: ((SocketAnyEvent) -> Void)?
private var currentReconnectAttempt = 0
private var handlers = [SocketEventHandler]()
private var reconnectTimer: NSTimer?
private var ackHandlers = SocketAckManager()
private(set) var currentAck = -1
private(set) var handleQueue = dispatch_get_main_queue()
private(set) var reconnectAttempts = -1
var waitingData = [SocketPacket]()
/**
Type safe way to create a new SocketIOClient. opts can be omitted
*/
public init(socketURL: String, options: Set<SocketIOClientOption> = []) {
self.options = options
if socketURL["https://"].matches().count != 0 {
self.options.insertIgnore(.Secure(true))
}
self.socketURL = socketURL["https?://"] <~ ""
for option in options {
switch option {
case let .ConnectParams(params):
connectParams = params
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.options.insertIgnore(.Path("/socket.io"))
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(var socketURL: String, options: Set<SocketIOClientOption>)`
*/
public convenience init(socketURL: String, options: NSDictionary?) {
self.init(socketURL: socketURL,
options: options?.toSocketOptionsSet() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Client is being deinit", type: logType)
engine?.close("Client Deinit")
}
private func addEngine() -> SocketEngineSpec {
DefaultSocketLogger.Logger.log("Adding engine", type: logType)
engine = SocketEngine(client: self, url: socketURL, options: options)
return engine!
}
private func clearReconnectTimer() {
reconnectTimer?.invalidate()
reconnectTimer = nil
}
@available(*, deprecated=6.0)
public func close() {
disconnect()
}
/**
Connect to the server.
*/
public func connect() {
connect(timeoutAfter: 0, withTimeoutHandler: nil)
}
/**
Connect to the server. If we aren't connected after timeoutAfter, call handler
*/
public func connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler 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().open(connectParams)
} else {
engine?.open(connectParams)
}
guard timeoutAfter != 0 else { return }
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
dispatch_after(time, handleQueue) {[weak self] in
if let this = self where this.status != .Connected {
this.status = .Closed
this.engine?.close("Connect timeout")
handler?()
}
}
}
private func createOnAck(items: [AnyObject]) -> OnAckCallback {
currentAck += 1
return {[weak self, ack = currentAck] timeout, callback in
if let this = self {
this.ackHandlers.addAck(ack, callback: callback)
dispatch_async(this.emitQueue) {
this._emit(items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, this.handleQueue) {
this.ackHandlers.timeoutAck(ack)
}
}
}
}
}
func didConnect() {
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .Connected
currentReconnectAttempt = 0
clearReconnectTimer()
// 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 != .Closed else {
return
}
DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason)
status = .Closed
reconnects = false
// Make sure the engine is actually dead.
engine?.close(reason)
handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/**
Disconnects the socket. Only reconnect the same socket if you know what you're doing.
Will turn off automatic reconnects.
*/
public func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
reconnects = false
didDisconnect("Disconnect")
}
/**
Send a message to the server
*/
public func emit(event: String, _ items: AnyObject...) {
emit(event, withItems: items)
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event: String, withItems items: [AnyObject]) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting \(event) when not connected"], isInternalMessage: true)
return
}
dispatch_async(emitQueue) {
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 {
return emitWithAck(event, withItems: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event: String, withItems items: [AnyObject]) -> OnAckCallback {
return createOnAck([event] + items)
}
private func _emit(data: [AnyObject], ack: Int? = nil) {
guard status == .Connected else {
handleEvent("error", data: ["Tried emitting when not connected"], isInternalMessage: true)
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str)
engine?.send(str, withData: packet.binary)
}
// If the server wants to know that the client received data
func emitAck(ack: Int, withItems items: [AnyObject]) {
dispatch_async(emitQueue) {
if self.status == .Connected {
let packet = SocketPacket.packetFromEmit(items, id: ack ?? -1, nsp: self.nsp, ack: true)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: self.logType, args: str)
self.engine?.send(str, withData: packet.binary)
}
}
}
public func engineDidClose(reason: String) {
waitingData.removeAll()
if status == .Closed || !reconnects {
didDisconnect(reason)
} else if status != .Reconnecting {
status = .Reconnecting
handleEvent("reconnect", data: [reason], isInternalMessage: true)
tryReconnect()
}
}
/// error
public func engineDidError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
handleEvent("error", data: [reason], isInternalMessage: true)
}
// Called when the socket gets an ack for something it sent
func handleAck(ack: Int, data: [AnyObject]) {
guard status == .Connected else {return}
DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data ?? "")
ackHandlers.executeAck(ack, items: data)
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event: String, data: [AnyObject], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .Connected || isInternalMessage else {
return
}
DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data ?? "")
dispatch_async(handleQueue) {
self.anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in self.handlers where handler.event == event {
handler.executeCallback(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)
*/
public func off(event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event)
handlers = handlers.filter { $0.event != event }
}
/**
Removes a handler with the specified UUID gotten from an `on` or `once`
*/
public func off(id id: NSUUID) {
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
*/
public func on(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event)
let handler = SocketEventHandler(event: event, id: NSUUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/**
Adds a single-use handler for an event.
Returns: A unique id for the handler
*/
public func once(event: String, callback: NormalCallback) -> NSUUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event)
let id = NSUUID()
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: (SocketAnyEvent) -> Void) {
anyHandler = handler
}
/**
Same as connect
*/
@available(*, deprecated=6.0)
public func open() {
connect()
}
public func parseEngineMessage(msg: String) {
DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg)
dispatch_async(parseQueue) {
self.parseSocketMessage(msg)
}
}
public func parseEngineBinaryData(data: NSData) {
dispatch_async(parseQueue) {
self.parseBinaryData(data)
}
}
/**
Tries to reconnect to the server.
*/
public func reconnect() {
tryReconnect()
}
/**
Removes all handlers.
Can be used after disconnecting to break any potential remaining retain cycles.
*/
public func removeAllHandlers() {
handlers.removeAll(keepCapacity: false)
}
private func tryReconnect() {
if reconnectTimer == nil {
DefaultSocketLogger.Logger.log("Starting reconnect", type: logType)
status = .Reconnecting
dispatch_async(dispatch_get_main_queue()) {
self.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self.reconnectWait),
target: self, selector: "_tryReconnect", userInfo: nil, repeats: true)
}
}
}
@objc private func _tryReconnect() {
if status == .Connected {
clearReconnectTimer()
return
}
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects {
clearReconnectTimer()
didDisconnect("Reconnect Failed")
return
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType)
handleEvent("reconnectAttempt", data: [reconnectAttempts - currentReconnectAttempt],
isInternalMessage: true)
currentReconnectAttempt += 1
connect()
}
}
// Test extensions
extension SocketIOClient {
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .Connected
}
func setTestEngine(engine: SocketEngineSpec?) {
self.engine = engine
}
func emitTest(event: String, _ data: AnyObject...) {
self._emit([event] + data)
}
}
+213
View File
@@ -0,0 +1,213 @@
//
// 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, Hashable {
func getSocketIOOptionValue() -> AnyObject
}
public enum SocketIOClientOption: ClientOption {
case ConnectParams([String: AnyObject])
case Cookies([NSHTTPCookie])
case ExtraHeaders([String: String])
case ForceNew(Bool)
case ForcePolling(Bool)
case ForceWebsockets(Bool)
case HandleQueue(dispatch_queue_t)
case Log(Bool)
case Logger(SocketLogger)
case Nsp(String)
case Path(String)
case Reconnects(Bool)
case ReconnectAttempts(Int)
case ReconnectWait(Int)
case Secure(Bool)
case SelfSigned(Bool)
case SessionDelegate(NSURLSessionDelegate)
case VoipEnabled(Bool)
public var description: String {
let description: String
switch self {
case .ConnectParams:
description = "connectParams"
case .Cookies:
description = "cookies"
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 .SessionDelegate:
description = "sessionDelegate"
case .VoipEnabled:
description = "voipEnabled"
}
return description
}
public var hashValue: Int {
return description.hashValue
}
func getSocketIOOptionValue() -> AnyObject {
let value: AnyObject
switch self {
case let .ConnectParams(params):
value = params
case let .Cookies(cookies):
value = cookies
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 .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
}
extension Set where Element: ClientOption {
mutating func insertIgnore(element: Element) {
if !contains(element) {
insert(element)
}
}
}
extension NSDictionary {
static func keyValueToSocketIOClientOption(key: String, value: AnyObject) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: AnyObject]):
return .ConnectParams(params)
case let ("reconnects", reconnects as Bool):
return .Reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .ReconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .ReconnectWait(wait)
case let ("forceNew", force as Bool):
return .ForceNew(force)
case let ("forcePolling", force as Bool):
return .ForcePolling(force)
case let ("forceWebsockets", force as Bool):
return .ForceWebsockets(force)
case let ("nsp", nsp as String):
return .Nsp(nsp)
case let ("cookies", cookies as [NSHTTPCookie]):
return .Cookies(cookies)
case let ("log", log as Bool):
return .Log(log)
case let ("logger", logger as SocketLogger):
return .Logger(logger)
case let ("sessionDelegate", delegate as NSURLSessionDelegate):
return .SessionDelegate(delegate)
case let ("path", path as String):
return .Path(path)
case let ("extraHeaders", headers as [String: String]):
return .ExtraHeaders(headers)
case let ("handleQueue", queue as dispatch_queue_t):
return .HandleQueue(queue)
case let ("voipEnabled", enable as Bool):
return .VoipEnabled(enable)
case let ("secure", secure as Bool):
return .Secure(secure)
case let ("selfSigned", selfSigned as Bool):
return .SelfSigned(selfSigned)
default:
return nil
}
}
func toSocketOptionsSet() -> Set<SocketIOClientOption> {
var options = Set<SocketIOClientOption>()
for (rawKey, value) in self {
if let key = rawKey as? String, opt = NSDictionary.keyValueToSocketIOClientOption(key, value: value) {
options.insertIgnore(opt)
}
}
return options
}
}
@@ -25,6 +25,8 @@
import Foundation
@objc public enum SocketIOClientStatus: Int, CustomStringConvertible {
case NotConnected, Closed, Connecting, Connected, Reconnecting
public var description: String {
switch self {
case NotConnected:
@@ -39,6 +41,4 @@ import Foundation
return "Reconnecting"
}
}
case NotConnected, Closed, Connecting, Connected, Reconnecting
}
@@ -24,9 +24,7 @@
import Foundation
var Logger: SocketLogger = DefaultSocketLogger()
public protocol SocketLogger {
public protocol SocketLogger: class {
/// Whether to log or not
var log: Bool {get set}
@@ -39,7 +37,7 @@ public protocol SocketLogger {
public extension SocketLogger {
func log(message: String, type: String, args: AnyObject...) {
abstractLog("Log", message: message, type: type, args: args)
abstractLog("LOG", message: message, type: type, args: args)
}
func error(message: String, type: String, args: AnyObject...) {
@@ -49,13 +47,15 @@ public extension SocketLogger {
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
guard log else { return }
let newArgs = args.map {arg -> CVarArgType in String(arg)}
let newArgs = args.map({arg -> CVarArgType in String(arg)})
let replaced = String(format: message, arguments: newArgs)
NSLog("%@ %@: %@", logType, type, replaced)
}
}
struct DefaultSocketLogger: SocketLogger {
class DefaultSocketLogger: SocketLogger {
static var Logger: SocketLogger = DefaultSocketLogger()
var log = false
}
@@ -21,14 +21,14 @@
// 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 {
private let placeholders: Int
private var currentPlace = 0
private static let logType = "SocketPacket"
private static let logType = "SocketPacket"
let nsp: String
let id: Int
@@ -36,28 +36,13 @@ struct SocketPacket {
enum PacketType: Int {
case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck
init?(str: String) {
if let int = Int(str), raw = PacketType(rawValue: int) {
self = raw
} else {
return nil
}
}
}
var args: [AnyObject]? {
var arr = data
if data.count == 0 {
return nil
var args: [AnyObject] {
if type == .Event || type == .BinaryEvent && data.count != 0 {
return Array(data.dropFirst())
} else {
if type == PacketType.Event || type == PacketType.BinaryEvent {
arr.removeAtIndex(0)
return arr
} else {
return arr
}
return data
}
}
@@ -69,7 +54,7 @@ struct SocketPacket {
}
var event: String {
return data[0] as? String ?? String(data[0])
return String(data[0])
}
var packetString: String {
@@ -87,22 +72,23 @@ struct SocketPacket {
}
mutating func addData(data: NSData) -> Bool {
if placeholders == currentPlace {
if placeholders == binary.count {
return true
}
binary.append(data)
currentPlace++
if placeholders == currentPlace {
currentPlace = 0
if placeholders == binary.count {
fillInPlaceholders()
return true
} else {
return false
}
}
private func completeMessage(var message: String, ack: Bool) -> String {
private func completeMessage(message: String, ack: Bool) -> String {
var restOfMessage = ""
if data.count == 0 {
return message + "]"
}
@@ -112,56 +98,54 @@ struct SocketPacket {
do {
let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(rawValue: 0))
let jsonString = NSString(data: jsonSend, encoding: NSUTF8StringEncoding)
let jsonString = String(data: jsonSend, encoding: NSUTF8StringEncoding)
message += jsonString! as String + ","
restOfMessage += jsonString! + ","
} catch {
Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType)
DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage",
type: SocketPacket.logType)
}
} else if var str = arg as? String {
str = str["\n"] ~= "\\\\n"
str = str["\r"] ~= "\\\\r"
message += "\"\(str)\","
} else if let str = arg as? String {
restOfMessage += "\"" + ((str["\n"] <~ "\\\\n")["\r"] <~ "\\\\r") + "\","
} else if arg is NSNull {
message += "null,"
restOfMessage += "null,"
} else {
message += "\(arg),"
restOfMessage += "\(arg),"
}
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
if restOfMessage != "" {
restOfMessage.removeAtIndex(restOfMessage.endIndex.predecessor())
}
return message + "]"
return message + restOfMessage + "]"
}
private func createAck() -> String {
let msg: String
let message: String
if type == PacketType.Ack {
if type == .Ack {
if nsp == "/" {
msg = "3\(id)["
message = "3\(id)["
} else {
msg = "3\(nsp),\(id)["
message = "3\(nsp),\(id)["
}
} else {
if nsp == "/" {
msg = "6\(binary.count)-\(id)["
message = "6\(binary.count)-\(id)["
} else {
msg = "6\(binary.count)-/\(nsp),\(id)["
message = "6\(binary.count)-\(nsp),\(id)["
}
}
return completeMessage(msg, ack: true)
return completeMessage(message, ack: true)
}
private func createMessageForEvent() -> String {
let message: String
if type == PacketType.Event {
if type == .Event {
if nsp == "/" {
if id == -1 {
message = "2["
@@ -197,7 +181,7 @@ struct SocketPacket {
private func createPacketString() -> String {
let str: String
if type == PacketType.Event || type == PacketType.BinaryEvent {
if type == .Event || type == .BinaryEvent {
str = createMessageForEvent()
} else {
str = createAck()
@@ -206,41 +190,30 @@ struct SocketPacket {
return str
}
mutating func fillInPlaceholders() {
for i in 0..<data.count {
if let str = data[i] as? String, num = str["~~(\\d)"].groups() {
data[i] = binary[Int(num[1])!]
} else if data[i] is NSDictionary || data[i] is NSArray {
data[i] = _fillInPlaceholders(data[i])
}
}
// 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)
}
private mutating func _fillInPlaceholders(data: AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return binary[Int(num[1])!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
let newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
let newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
// Helper method that looks for placeholder strings
// If object is a collection it will recurse
// Returns the object if it is not a placeholder string or the corresponding
// binary data
private func _fillInPlaceholders(object: AnyObject) -> AnyObject {
switch object {
case let string as String where string["~~(\\d)"].groups() != nil:
return binary[Int(string["~~(\\d)"].groups()![1])!]
case let dict as NSDictionary:
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = _fillInPlaceholders(keyValue.1)
return cur
})
case let arr as [AnyObject]:
return arr.map(_fillInPlaceholders)
default:
return object
}
}
}
@@ -249,15 +222,15 @@ extension SocketPacket {
private static func findType(binCount: Int, ack: Bool) -> PacketType {
switch binCount {
case 0 where !ack:
return PacketType.Event
return .Event
case 0 where ack:
return PacketType.Ack
return .Ack
case _ where !ack:
return PacketType.BinaryEvent
return .BinaryEvent
case _ where ack:
return PacketType.BinaryAck
return .BinaryAck
default:
return PacketType.Error
return .Error
}
}
@@ -271,44 +244,31 @@ extension SocketPacket {
}
private extension SocketPacket {
// Recursive function that looks for NSData in collections
static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": binary.count]
let placeholder = ["_placeholder": true, "num": binary.count]
switch data {
case let bin as NSData:
binary.append(bin)
return placeholder
} else if var arr = data as? [AnyObject] {
for i in 0..<arr.count {
arr[i] = shred(arr[i], binary: &binary)
}
return arr
} else if let dict = data as? NSDictionary {
let mutDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
mutDict[key as! NSCopying] = shred(value, binary: &binary)
}
return mutDict
} else {
case let arr as [AnyObject]:
return arr.map({shred($0, binary: &binary)})
case let dict as NSDictionary:
return dict.reduce(NSMutableDictionary(), combine: {cur, keyValue in
cur[keyValue.0 as! NSCopying] = shred(keyValue.1, binary: &binary)
return cur
})
default:
return data
}
}
static func deconstructData(var data: [AnyObject]) -> ([AnyObject], [NSData]) {
// Removes binary data from emit data
// Returns a type containing the de-binaryed data and the binary
static func deconstructData(data: [AnyObject]) -> ([AnyObject], [NSData]) {
var binary = [NSData]()
for i in 0..<data.count {
if data[i] is NSArray || data[i] is NSDictionary {
data[i] = shred(data[i], binary: &binary)
} else if let bin = data[i] as? NSData {
data[i] = ["_placeholder" :true, "num": binary.count]
binary.append(bin)
}
}
return (data, binary)
return (data.map({shred($0, binary: &binary)}), binary)
}
}
+182
View File
@@ -0,0 +1,182 @@
//
// 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: SocketClientSpec {
func parseBinaryData(data: NSData)
func parseSocketMessage(message: String)
}
extension SocketParsable {
private func isCorrectNamespace(nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(p: SocketPacket) {
if p.nsp == "/" && nsp != "/" {
joinNamespace(nsp)
} else if p.nsp != "/" && nsp == "/" {
didConnect()
} 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):
waitingData.append(pack)
case .BinaryAck where isCorrectNamespace(pack.nsp):
waitingData.append(pack)
case .Connect:
handleConnect(pack)
case .Disconnect:
didDisconnect("Got Disconnect")
case .Error:
handleEvent("error", data: pack.data, isInternalMessage: false, 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 parser = SocketStringReader(message: message)
guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else {
return .Left("Invalid packet type")
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, nsp: "/"))
}
var namespace: String?
var placeholders = -1
if type == .BinaryEvent || type == .BinaryAck {
if let holders = Int(parser.readUntilStringOccurence("-")) {
placeholders = holders
} else {
return .Left("Invalid packet")
}
}
if parser.currentCharacter == "/" {
namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd()
}
if !parser.hasNext {
return .Right(SocketPacket(type: type, id: -1,
nsp: namespace ?? "/", placeholders: placeholders))
}
var idString = ""
if type == .Error {
parser.advanceIndexBy(-1)
}
while parser.hasNext && type != .Error {
if let int = Int(parser.read(1)) {
idString += String(int)
} else {
parser.advanceIndexBy(-2)
break
}
}
let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex]
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] <~ "\"~~$2\""
switch parseData(noPlaceholders) {
case let .Left(err):
// If first you don't succeed, try again
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
} else {
return .Left(err)
}
case let .Right(data):
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace ?? "/", placeholders: placeholders))
}
}
// Parses data for events
private func parseData(data: String) -> Either<String, [AnyObject]> {
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] {
return .Right(arr)
} else {
return .Left("Expected data array")
}
} 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: NSData) {
guard !waitingData.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingData[waitingData.count - 1].addData(data) else {
return
}
let packet = waitingData.removeLast()
if packet.type != .BinaryAck {
handleEvent(packet.event, data: packet.args ?? [],
isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
}
}
File renamed without changes.
@@ -24,10 +24,11 @@
import Foundation
public typealias AckCallback = (NSArray?) -> Void
public typealias AckEmitter = (AnyObject...) -> Void
public typealias AckEmitterObjectiveC = (NSArray) -> Void
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias NormalCallbackObjectiveC = (NSArray?, AckEmitterObjectiveC?) -> Void
public typealias OnAckCallback = (timeoutAfter:UInt64, callback:AckCallback) -> Void
public typealias AckCallback = ([AnyObject]) -> Void
public typealias NormalCallback = ([AnyObject], SocketAckEmitter) -> Void
public typealias OnAckCallback = (timeoutAfter: UInt64, callback: AckCallback) -> Void
enum Either<E, V> {
case Left(E)
case Right(V)
}
@@ -13,9 +13,11 @@
import Foundation
infix operator <~ { associativity none precedence 130 }
private var swiftRegexCache = [String: NSRegularExpression]()
internal class SwiftRegex: NSObject, BooleanType {
internal final class SwiftRegex: NSObject, BooleanType {
var target:String
var regex: NSRegularExpression
@@ -29,8 +31,8 @@ internal class SwiftRegex: NSObject, BooleanType {
NSRegularExpressionOptions.DotMatchesLineSeparators)
swiftRegexCache[pattern] = regex
self.regex = regex
} catch let error1 as NSError {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error1)")
} catch let error as NSError {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
@@ -41,12 +43,12 @@ internal class SwiftRegex: NSObject, BooleanType {
fatalError("SwiftRegex: \(message)")
}
private final var targetRange: NSRange {
private var targetRange: NSRange {
return NSRange(location: 0,length: target.utf16.count)
}
private final func substring(range: NSRange) -> String? {
if ( range.location != NSNotFound ) {
private func substring(range: NSRange) -> String? {
if range.location != NSNotFound {
return (target as NSString).substringWithRange(range)
} else {
return nil
@@ -70,20 +72,19 @@ internal class SwiftRegex: NSObject, BooleanType {
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
}
private 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 {
private func groupsForMatch(match: NSTextCheckingResult?) -> [String]? {
guard let match = match else {
return 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
}
subscript(groupno: Int) -> String? {
@@ -124,7 +125,7 @@ internal class SwiftRegex: NSObject, BooleanType {
}
func allGroups() -> [[String]?] {
return matchResults().map {self.groupsForMatch($0)}
return matchResults().map { self.groupsForMatch($0) }
}
func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
@@ -169,36 +170,9 @@ extension String {
}
}
func ~= (left: SwiftRegex, right: String) -> String {
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: [])
}
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: [])
}
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: [])
}
func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: [])
}
File diff suppressed because it is too large. Load diff