Compare commits

...
183 Commits
Author SHA1 Message Date
Erik 31a41072c3 fix warning 2015-04-08 17:14:56 -04:00
Erik c325706228 Release for Swift 1.2. For Swift 1.1 use version v1.5.2 2015-04-08 17:12:27 -04:00
Erik a0dff2fea4 Merge branch '1.2' 2015-04-08 17:07:59 -04:00
Erik acdb29dca4 add message about @objc_block 2015-04-08 11:10:35 -04:00
Erik 0c3e25ef3c bump version 2015-04-07 21:58:35 -04:00
Erik d8ea3a3c11 merge master 2015-04-07 21:56:36 -04:00
Erik ac28c7541e fix socketio/socket.io-client-swift#46 2015-04-07 21:53:14 -04:00
Erik fcc202ab04 fix indentation 2015-04-07 13:33:48 -04:00
Erik eb56a8de9c merge master 2015-04-06 13:05:21 -04:00
Erik c2d488e35c bump version 2015-04-06 13:00:16 -04:00
Erik eb9d2bc744 better closing 2015-04-06 12:59:39 -04:00
Erik a4e81fee6a fix outstanding poll messages after switch to websockets 2015-04-06 12:49:39 -04:00
Erik 9489676009 use weak references to client 2015-04-06 11:56:47 -04:00
Erik 6e56869ef0 add note about emitwithack 2015-04-06 09:30:22 -04:00
Erik dde941f4af Merge branch 'master' into 1.2 2015-04-04 12:22:47 -04:00
Erik 3ebc596ab8 clean up readme 2015-04-04 12:22:37 -04:00
Erik ce81bb2a33 Merge branch 'master' into 1.2 2015-04-04 12:20:51 -04:00
Erik 1349b01b2b fix api on readme 2015-04-04 12:19:14 -04:00
Erik 63cbf49448 fixes 2015-04-04 10:47:53 -04:00
Erik a17f2b6e7a merge master 2015-04-03 16:37:02 -04:00
Erik a1f24ff281 bump version 2015-04-03 16:19:32 -04:00
Erik 838dade0fa Fix messages getting stuck in post 2015-04-03 16:18:15 -04:00
Erik d4470a9084 fix readme 2015-04-03 16:05:47 -04:00
Erik affd792334 redo acks 2015-04-03 16:04:50 -04:00
Erik c1b0d3abeb merge master 2015-04-01 16:08:23 -04:00
Erik Little 38163d29cb Merge pull request #40 from socketio/betterreadme
Betterreadme
2015-04-01 15:59:29 -04:00
Erik 2952120fc1 tweak readme 2015-04-01 15:49:06 -04:00
Erik Little 7641ffef41 Update README.md 2015-04-01 15:44:19 -04:00
Erik 58d2693910 Fix readme 2015-04-01 15:43:46 -04:00
Erik dd28b1747c add connection options 2015-04-01 15:42:23 -04:00
Erik Little e90ecb81be Update README.md 2015-04-01 15:08:26 -04:00
Erik 060060f5c2 work on readme 2015-04-01 15:02:25 -04:00
Erik f7b064d80f refactor SocketEngine#sendPing 2015-04-01 14:49:01 -04:00
Erik 918d40d68c Merge branch 'master' into 1.2 2015-03-31 14:27:35 -04:00
Erik 01a699c7c6 add return to pong message 2015-03-31 00:04:09 -04:00
Erik 5fffa685e9 merge master 2015-03-28 16:58:12 -04:00
Erik 7b7ccb87da bump version 2015-03-28 16:57:09 -04:00
Erik 93f1cfe9dc fix socketio/socket.io-client-swift#36 2015-03-28 16:54:48 -04:00
Erik da1cf9eb89 socketio/socket.io-client-swift#37 2015-03-28 16:16:03 -04:00
Erik a61f1c8484 merge master 2015-03-27 12:41:49 -04:00
Erik 57731bebf8 Fix for first polling messages with unicode 2015-03-27 12:35:12 -04:00
Erik 81d58fbd69 fix nsp for default 2015-03-27 12:22:59 -04:00
Erik c4731dc298 don't crash if nsp starts with / 2015-03-27 12:21:05 -04:00
Erik 18a561f78a update READEME.md 2015-03-27 12:17:57 -04:00
Erik 85019cca09 bump version 2015-03-27 12:15:16 -04:00
Erik a4361a04b6 style 2015-03-27 12:14:45 -04:00
Erik ffcd841267 Fix binary acks 2015-03-27 12:13:06 -04:00
Erik d308111a8f fix for 1.2 2015-03-27 11:35:02 -04:00
Erik f669267f51 Merge branch 'master' into 1.2 2015-03-27 11:30:41 -04:00
Erik 98e0c355f9 add forcewebsockets option 2015-03-27 09:35:39 -04:00
Erik 2cae405d29 try and avoid bad engine states 2015-03-26 13:15:43 -04:00
Erik f008f116a6 fix socketio/socket.io-client-swift#27 2015-03-26 10:13:30 -04:00
Erik 77532acbd3 merge master 2015-03-25 17:03:55 -04:00
Erik 9512c8b9ac change api 2015-03-25 12:02:45 -04:00
Erik b0020997c4 don't use default arg 2015-03-25 11:59:03 -04:00
Erik ce7c9c2c15 bump version 2015-03-25 11:52:55 -04:00
Erik 90f50a1c7e add missing file 2015-03-25 11:51:55 -04:00
Erik 182ba0017b fix nuclearace/Socket.IO-Client-Swift#12 better closing 2015-03-25 11:50:25 -04:00
Erik 5b897ddfea indentation 2015-03-24 14:13:21 -04:00
Erik 4e6b686f37 Merge branch 'master' into 1.2 2015-03-24 12:26:49 -04:00
Erik 78aba627a2 bump version 2015-03-24 11:17:29 -04:00
Erik 9044de53d9 fix socketio/socket.io-client-swift#25 2015-03-24 11:05:03 -04:00
Erik e34cb61ae2 merge master 2015-03-23 11:40:10 -04:00
Erik 61ad14f23b refactor remaking packets 2015-03-23 11:34:28 -04:00
Erik 03c24659f2 use static property 2015-03-22 15:13:44 -04:00
Erik 5e1a19f638 fix for 1.2 2015-03-22 15:12:01 -04:00
Erik 1d70305743 merge master 2015-03-22 15:10:12 -04:00
Erik 4c7b3175ca bump version 2015-03-22 14:41:15 -04:00
Erik 5533545adb performance 2015-03-22 13:19:53 -04:00
Erik 8fa8944672 fix for no args acks 2015-03-22 11:05:56 -04:00
Erik dee508c0f7 fix race condition 2015-03-22 11:02:31 -04:00
Erik 4de422e7f1 tweaks 2015-03-22 09:53:25 -04:00
Erik 4629565aaf clean up 2015-03-22 08:39:24 -04:00
Erik 8b893ad85e refactor 2015-03-21 18:16:09 -04:00
Erik 8b3e4a2c43 fix for 1.2 2015-03-21 11:44:49 -04:00
Erik 504d0fbd18 merge master 2015-03-21 11:42:52 -04:00
Erik 6985efd7fb Regular ack doesn't matter 2015-03-20 20:52:34 -04:00
Erik 6ac69d1c2d fix for acks 2015-03-20 20:51:06 -04:00
Erik b8b12313fa Merge branch 'master' into performance 2015-03-20 20:25:53 -04:00
Erik 5388084c79 seems to be on par with the native js-client most of the time 2015-03-20 20:24:59 -04:00
Erik Little 48bcada835 Update SocketEngineClient.swift 2015-03-20 20:22:31 -04:00
Erik cf65f56a1d fix namespaces 2015-03-20 16:05:51 -04:00
Erik 18b8f992d9 Tweaks for performance 2015-03-20 15:23:38 -04:00
Erik b576294232 merge master 2015-03-20 11:03:28 -04:00
Erik 2837c7c42c bump version 2015-03-20 10:54:52 -04:00
Erik 4832be5c8a better parsing 2015-03-20 10:51:26 -04:00
Erik d70db2a8be merge master 2015-03-19 15:05:29 -04:00
Erik cbc59d6004 fix race condition 2015-03-19 14:13:03 -04:00
Erik 72d5c07de1 refactor 2015-03-19 14:04:02 -04:00
Erik 54b2da8395 work on redesign 2015-03-19 13:22:58 -04:00
Erik Little 5175791513 Update README.md 2015-03-19 11:07:16 -04:00
Erik 2f82de9502 bump version 2015-03-19 08:37:10 -04:00
Erik 457a33c677 fix for 1.2 2015-03-19 08:31:30 -04:00
Erik 15954f36f5 Merge branch 'master' into 1.2 2015-03-19 08:30:08 -04:00
Erik fd3dbee71c fixes 2015-03-19 08:23:43 -04:00
Erik 911cac9c23 work on parser 2015-03-18 19:54:51 -04:00
Erik d13d185011 work on parser 2015-03-18 19:21:04 -04:00
Erik 84752b463a merge master 2015-03-18 18:39:53 -04:00
Erik 66aaa52120 bump version 2015-03-18 18:25:05 -04:00
Erik 5b180a0a6d fix socketio/socket.io-client-swift#20, change objc api 2015-03-18 18:04:43 -04:00
Erik bb26dd05f8 merge master 2015-03-18 14:03:53 -04:00
Erik 0ca13c5496 update readme 2015-03-18 13:57:20 -04:00
Erik 1a5487fec5 Merge branch 'auth' 2015-03-18 13:27:06 -04:00
Erik 07f2d7465a merge master 2015-03-18 13:11:02 -04:00
Erik 89ae9bd349 handle utf8 in polling better 2015-03-18 13:05:39 -04:00
Erik c67e7a3003 work on socketio/socket.io-client-swift#11 2015-03-18 09:19:22 -04:00
Erik 472ba50058 bump version 2015-03-18 09:15:13 -04:00
Erik ab77d7260e work on socketio/socket.io-client-swift#17 2015-03-17 23:57:31 -04:00
Erik 028afcaa2c Merge branch 'master' into 1.2 2015-03-17 12:12:37 -04:00
Erik ac31b4a788 hopefully fix nuclearace/Socket.IO-Client-Swift#27 2015-03-17 12:12:30 -04:00
Erik 7d08f962d5 fix socketio/socket.io-client-swift#16 2015-03-16 20:49:02 -04:00
Erik 2712461044 fix #26 2015-03-16 17:58:12 -04:00
Erik 3ebdd9f7eb fix #26 2015-03-16 17:43:54 -04:00
Erik 3e260152cb update for 1.2 2015-03-16 16:30:28 -04:00
Erik 937090458c merge master 2015-03-16 16:08:49 -04:00
Erik 44e2781076 #11 2015-03-16 13:24:25 -04:00
Erik fea16879e1 Receive doubly encoded utf8 in polling until https://github.com/Automattic/engine.io/issues/315 is fixed properly 2015-03-16 13:12:37 -04:00
Erik Little e932d0a26b Fix copypasta 2015-03-16 11:53:14 -04:00
Erik 6e84950c05 API changed, change version 2015-03-16 11:49:10 -04:00
Erik 90187aa458 fix convenience constructor. Bump version 2015-03-16 11:47:42 -04:00
Erik 68da96f37d fix for objc 2015-03-16 09:23:21 -04:00
Erik ffd92d7bb4 Merge branch 'timeouts' 2015-03-16 09:22:32 -04:00
Erik c6d0331d50 merge timeouts fixes for 1.2 2015-03-16 09:06:45 -04:00
Erik 7765e57a11 Merge branch 'timeouts' into 1.2 2015-03-16 09:01:49 -04:00
Erik 18c25fabdf merge master 2015-03-16 08:55:37 -04:00
Erik c103734035 work on parsing stuff 2015-03-15 23:41:01 -04:00
Erik 2022f282c9 add no timeout 2015-03-14 19:46:03 -04:00
Erik d75457f397 Merge branch 'master' into timeouts 2015-03-14 19:12:09 -04:00
Erik bb6bd2b4ca fix race condition in polling 2015-03-14 19:09:54 -04:00
Erik c177671112 work on #23 2015-03-14 14:11:32 -04:00
Erik 94f3e3a6b9 merge master 2015-03-13 10:10:49 -04:00
Erik 4551cad9e1 update 1.2 2015-03-13 10:08:41 -04:00
Erik 2cc68aead6 Don't poll on sendPollMessage 2015-03-13 09:51:53 -04:00
Erik 1f05bde09b small tweaks 2015-03-13 09:09:37 -04:00
Erik 5b019a91c5 start refactoring 2015-03-12 17:54:17 -04:00
Erik a28e924b04 forgot one 2015-03-12 16:53:11 -04:00
Erik f7bf9d4e6b bump version 2015-03-12 16:34:36 -04:00
Erik 37537de213 change visibility of socketioclient members 2015-03-12 16:34:08 -04:00
Erik 560235353d merge master 2015-03-12 14:49:00 -04:00
Erik 8e7c8444d3 set socket sid 2015-03-12 13:44:55 -04:00
Erik 74939f1cea fixes 2015-03-12 13:38:06 -04:00
Erik ab5cccce85 fix binary in dictionaries 2015-03-12 11:38:45 -04:00
Erik 58362f6352 clean up readme 2015-03-12 10:27:37 -04:00
Erik abbd8e6a67 update 2015-03-12 10:19:59 -04:00
Erik Little 3ba793acf1 Merge pull request #8 from banjun/readme-cocoapods
[README] add CocoaPods in Installation section
2015-03-12 10:19:27 -04:00
banjun ea20dc809e [README] add CocoaPods in Installation section 2015-03-12 22:58:00 +09:00
Erik 3e5fe4009c Really update it 2015-03-12 09:33:59 -04:00
Erik a84aa31489 update podspec 2015-03-12 09:32:12 -04:00
Erik 8f7f43f83e add osx 2015-03-12 09:31:27 -04:00
Erik 30cd0bd6cd update thing 2015-03-12 09:17:49 -04:00
Erik Little ac2bc13b11 Merge pull request #7 from banjun/cocoapods
CocoaPods podspec for v1.1.0
2015-03-12 09:08:17 -04:00
banjun 33f3ef4846 add podspec for v1.1.0 and LICENSE 2015-03-12 19:59:49 +09:00
Erik f14d9ef5ff add new stuff to 1.2 2015-03-11 18:08:05 -04:00
Erik 2e451e5185 trim more 2015-03-11 18:05:25 -04:00
Erik 114ce4ca0f trim example 2015-03-11 17:42:51 -04:00
Erik 8c02f5ef7b update readme with new methods 2015-03-11 17:38:27 -04:00
Erik 711ce8d8c4 fixes. add better objective-c support 2015-03-11 17:33:21 -04:00
Erik 8365ded215 Use starscream for websockets. Execute emitAcks on the main queue. 2015-03-11 13:33:54 -04:00
Erik 94d715aaf9 add link to example project 2015-03-07 19:48:41 -05:00
Erik 1ac05d9790 add new things to 1.2 2015-03-06 23:41:15 -05:00
Erik 02b1314a3d fix emit with no args 2015-03-02 13:52:01 -05:00
Erik 211dc1dd22 Merge branch '1.2' of https://github.com/nuclearace/Socket.IO-Client-Swift into 1.2 2015-02-24 18:33:23 -05:00
Erik e7973ba88f I was being stupid again 2015-02-24 18:33:17 -05:00
Erik Little 43ccf6dd45 Remove ackhandlers 2015-02-24 18:16:02 -05:00
Erik 3fbc396d85 send close event 2015-02-24 13:25:03 -05:00
Erik Little ecd76d6106 Update README.md 2015-02-24 13:07:07 -05:00
Erik Little 50ac79e07e Update README.md 2015-02-24 13:03:34 -05:00
Erik 5b9537065f #15 add connectWithParams 2015-02-24 12:59:56 -05:00
Erik Little 516d9b3eea Why did I do that 2015-02-23 17:24:18 -05:00
Erik Little 306ac47168 Remove println 2015-02-23 15:14:12 -05:00
Erik 170b1bc836 API CHANGE. See README 2015-02-23 15:08:38 -05:00
Erik 44de79d8c5 dispatch events on main queue 2015-02-15 18:51:43 -05:00
Erik Little 5d8479ed36 Update README.md 2015-02-15 13:22:19 -05:00
Erik 3754bd572a handle acks from the server 2015-02-15 13:17:36 -05:00
Erik Little 12b8f3ef1f Update README.md 2015-02-14 18:22:24 -05:00
Erik 308983c6c7 fix binary ack 2015-02-14 18:12:57 -05:00
Erik 216d8cae1e Add acks, still needs more testing 2015-02-14 17:36:34 -05:00
Erik Little c88febc5bc Update README.md 2015-02-14 00:11:13 -05:00
Erik 5f179ac278 don't async handlers, change ioURL 2015-02-13 23:37:06 -05:00
Erik f826ca4b8e Fix weird optimization bug 2015-02-13 18:16:09 -05:00
Erik b53d22f3a2 Use dispatch queues for buffering emitting and recieving 2015-02-13 17:07:04 -05:00
Erik 6d6ac0fc74 clean up swiftregex 2015-02-11 11:56:14 -05:00
Erik ca00926647 swift 1.2 2015-02-09 17:06:45 -05:00
15 changed files with 2496 additions and 1583 deletions

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
The MIT License (MIT)
Copyright (c) 2014-2015 Erik Little
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.
This library makes use of the following third party libraries:
Starscream
----------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+98 -138
View File
@@ -1,30 +1,106 @@
Socket.IO-Client-Swift
======================
#Socket.IO-Client-Swift
Socket.IO-client for iOS/OS X.
Socket.IO-client for Swift. Supports ws/wss/polling connections and binary. For socket.io 1.0+ and Swift 1.1.
##Example
```swift
let socket = SocketIOClient(socketURL: "localhost:8080")
For Swift 1.2 use the 1.2 branch.
socket.on("connect") {data, ack in
println("socket connected")
}
Installation
============
1. Requires linking [SocketRocket](https://github.com/square/SocketRocket) against your xcode project. (Be sure to link the [frameworks](https://github.com/square/SocketRocket#framework-dependencies) required by SocketRocket)
2. Create a bridging header for SocketRocket
3. Copy the SwiftIO folder into your xcode project
socket.on("currentAmount") {data, ack in
if let cur = data?[0] as? Double {
socket.emitWithAck("canUpdate", cur)(timeout: 0) {data in
socket.emit("update", ["amount": cur + 2.50])
}
API
===
Constructor
ack?("Got your currentAmount", "dude")
}
}
// Connect
socket.connect()
```
##Objective-C Example
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" options:nil];
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
NSLog(@"connected");
[socket emitObjc:@"echo" withItems:@[@"echo test"]];
[socket emitWithAckObjc:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
NSLog(@"Got ack");
});
}];
```
##Features
- Supports socket.io 1.0+
- Supports binary
- Supports Polling and WebSockets
- Supports TLS/SSL
- Can be used from Objective-C
##Installation
Manually (iOS 7+)
-----------------
1. Copy the SwiftIO folder into your Xcode project!
CocoaPods 0.36.0 or later (iOS 8+)
------------------
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Socket.IO-Client-Swift', '~> 1.3.2' # Or latest version
```
Install pods:
```
$ pod install
```
Import in your swift file:
```swift
import Socket_IO_Client_Swift
```
##API
Constructors
-----------
`init(socketURL: String, opts:[String: AnyObject]? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values. See example)
`init(socketURL: String, opts:NSDictionary? = nil)` - Constructs a new client for the given URL. opts can be omitted (will use default values)
`convenience init(socketURL: String, options:NSDictionary?)` - Same as above, but meant for Objective-C. See Objective-C Example.
Options
-------
- `reconnects: Bool` Default is `true`
- `reconnectAttempts: Int` Default is `-1` (infinite tries)
- `reconnectWait: Int` Default is `10`
- `forcePolling: Bool` Default is `false`. `true` forces the client to use xhr-polling.
- `forceWebsockets: Bool` Default is `false`. `true` forces the client to use WebSockets.
- `nsp: String` Default is `"/"`
- `cookies: [NSHTTPCookie]?` An array of NSHTTPCookies. Passed during the handshake. Default is nil.
Methods
-------
1. `socket.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. `socket.onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
3. `socket.emit(event:String, args:AnyObject...)` - Sends a message. Can send multiple args.
4. `socket.emitWithAck(event:String, args:AnyObject...) -> SocketAckHandler` - Sends a message that requests an acknowledgement from the server. Returns a SocketAckHandler which you can use to add an onAck handler. See example.
5. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
6. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
7. `socket.close()` - Closes the socket. Once a socket is closed it should not be reopened.
1. `on(name:String, callback:((data:NSArray?, ack:AckEmitter?) -> Void))` - Adds a handler for an event. Items are passed by an array. `ack` can be used to send an ack when one is requested. See example.
2. `onAny(callback:((event:String, items:AnyObject?)) -> Void)` - Adds a handler for all events. It will be called on any received event.
3. `emit(event:String, _ items:AnyObject...)` - Sends a message. Can send multiple items.
4. `emitObjc(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
6. `emitWithAckObjc(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
Events
------
@@ -34,124 +110,8 @@ Events
4. `reconnect` - Emitted when the connection is starting to reconnect.
5. `reconnectAttempt` - Emitted when attempting to reconnect.
Example
=======
```swift
// opts can be omitted, will use default values
let socket = SocketIOClient(socketURL: "https://localhost:8080", opts: [
"reconnects": true, // default true
"reconnectAttempts": 5, // default -1 (infinite tries)
"reconnectWait": 5, // default 10
"nsp": "swift", // connects to the specified namespace. Default is /
"forcePolling": true // if true, the socket will only use XHR polling, default is false (polling/WebSockets)
])
// Called on every event
socket.onAny {println("got event: \($0.event) with items \($0.items)")}
// Socket Events
socket.on("connect") {data, ack in
println("socket connected")
// Sending messages
socket.emit("testEcho")
socket.emit("testObject", [
"data": true
])
// Sending multiple items per message
socket.emit("multTest", [1], 1.4, 1, "true",
true, ["test": "foo"], "bar")
}
// Requesting acks, and responding to acks
socket.on("ackEvent") {data, ack in
if let str = data?[0] as? String {
println("Got ackEvent")
}
socket.emitWithAck("ackTest", "test").onAck {data in
println(data?[0])
}
ack?("Got your event", "dude")
}
socket.on("disconnect") {data, ack in
if let reason = data?[0] as? String {
println("Socket disconnected: \(reason)")
}
}
socket.on("reconnect") {data, ack in
if let reason = data?[0] as? String {
println("Socket reconnecting: \(reason)")
}
}
socket.on("reconnectAttempt") {data, ack in
if let triesLeft = data?[0] as? Int {
println(triesLeft)
}
}
// End Socket Events
socket.on("jsonTest") {data, ack in
if let json = data?[0] as? NSDictionary {
println(json["test"]!) // foo bar
}
}
// Event items are passed by an array
socket.on("multipleItems") {data, ack in
if data == nil {
return
}
if let str = data![0] as? String {
println(str)
}
if let arr = data![1] as? [Int] {
println(arr)
}
if let obj = data![4] as? NSDictionary {
println(obj["test"])
}
}
// Recieving binary
socket.on("dataTest") {data, ack in
if let data = data?[0] as? NSData {
println("data is binary")
}
}
socket.on("objectDataTest") {data, ack in
if let dict = data?[0] as? NSDictionary {
if let data = dict["data"] as? NSData {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Got data: \(string!)")
}
}
}
// Connecting
socket.connect()
// Sending binary
socket.emit("testData", [
"data": "Hello World".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!,
"test": true])
```
Detailed Example
================
##Detailed Example
A more detailed example can be found [here](https://github.com/nuclearace/socket.io-client-swift-example)
License
=======
##License
MIT
+19
View File
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "2.0.0"
s.summary = "Socket.IO-client for Swift"
s.description = <<-DESC
Socket.IO-client for Swift.
Supports ws/wss/polling connections and binary.
For socket.io 1.0+ and Swift 1.1.
DESC
s.homepage = "https://github.com/socketio/socket.io-client-swift"
s.license = { :type => 'MIT' }
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.0.0' }
s.source_files = "SwiftIO/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
+63
View File
@@ -0,0 +1,63 @@
//
// SocketAckMap.swift
// SocketIO-Swift
//
// Created by Erik Little on 4/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
// @objc_block is undocumented, but is used because Swift assumes that all
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
// And the way things are done here, the bridging fails to copy the block in
// SocketAckMap#addAck
public typealias AckCallback = @objc_block (NSArray?) -> Void
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
struct SocketAckMap {
private var acks = [Int: AckCallback]()
private var waiting = [Int: Bool]()
mutating func addAck(ack:Int, callback:AckCallback) {
waiting[ack] = true
acks[ack] = callback
}
mutating func executeAck(ack:Int, items:[AnyObject]?) {
let callback = acks[ack]
waiting[ack] = false
dispatch_async(dispatch_get_main_queue()) {
callback?(items)
return
}
acks.removeValueForKey(ack)
}
mutating func timeoutAck(ack:Int) {
if waiting[ack] != nil && waiting[ack]! {
acks[ack]?(["NO ACK"])
}
acks.removeValueForKey(ack)
waiting.removeValueForKey(ack)
}
}
@@ -1,9 +1,9 @@
//
// SocketAckHandler.swift
// SocketAnyEvent.swift
// Socket.IO-Swift
//
// Created by Erik Little on 2/14/15.
// Created by Erik Little on 3/28/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
@@ -24,19 +24,12 @@
import Foundation
typealias AckCallback = (NSArray?) -> Void
class SocketAckHandler {
let ackNum:Int!
let event:String!
var callback:AckCallback?
@objc public class SocketAnyEvent {
public let event:String!
public var items:[AnyObject]?
init(event:String, ackNum:Int = 0) {
self.ackNum = ackNum
init(event:String, items:[AnyObject]?) {
self.event = event
}
func onAck(callback:AckCallback) {
self.callback = callback
self.items = items
}
}
+409 -319
View File
@@ -24,19 +24,16 @@
import Foundation
// This is used because in Swift 1.1, turning on -O causes a
// memory access violation in SocketEngine#parseEngineMessage
private var fixSwift:AnyObject?
extension String {
private var length:Int {
return countElements(self)
return count(self)
}
}
private typealias PollWaitQueue = [() -> Void]
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private enum PacketType: String {
public enum PacketType:String {
case OPEN = "0"
case CLOSE = "1"
case PING = "2"
@@ -46,27 +43,35 @@ private enum PacketType: String {
case NOOP = "6"
}
class SocketEngine: NSObject, SRWebSocketDelegate {
unowned let client:SocketIOClient
public class SocketEngine: NSObject, WebSocketDelegate {
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create(
"emitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create(
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineParseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create(
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
"engineHandleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingTimer:NSTimer?
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = PollWaitQueue()
private let session:NSURLSession!
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
var connected = false
var connected:Bool {
return self._connected
}
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var pingInterval:Int?
var polling:Bool {
return self._polling
@@ -77,20 +82,30 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
var websocket:Bool {
return self._websocket
}
var ws:SRWebSocket?
init(client:SocketIOClient, forcePolling:Bool = false) {
self.client = client
self.forcePolling = forcePolling
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: nil, delegateQueue: self.workQueue)
var ws:WebSocket?
public init(client:SocketEngineClient, forcePolling:Bool,
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
self.client = client
self.forcePolling = forcePolling
self.forceWebsockets = forceWebsockets
self.cookies = cookies
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: nil, delegateQueue: self.workQueue)
}
func close() {
public func close(#fast:Bool) {
self.pingTimer?.invalidate()
self.send(PacketType.CLOSE.rawValue)
self.closed = true
self.write("", withType: PacketType.CLOSE, withData: nil)
self.ws?.disconnect()
if fast || self.polling {
self.client?.didForceClose("Disconnect")
}
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if self.websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
@@ -102,33 +117,37 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
var url = "\(self.client.socketURL)/socket.io/?transport="
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
if self.client == nil {
return ("", "")
}
var url = "\(self.client!.socketURL)/socket.io/?transport="
var urlPolling:String
var urlWebSocket:String
if self.client.secure {
if self.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(
NSCharacterSet.URLHostAllowedCharacterSet())!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as String).stringByAddingPercentEncodingWithAllowedCharacters(
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLHostAllowedCharacterSet())!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
@@ -138,59 +157,105 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocket(andConnect connect:Bool) {
self.ws = WebSocket(url: NSURL(string: self.urlWebSocket! + "&sid=\(self.sid)")!)
self.ws?.queue = self.handleQueue
self.ws?.delegate = self
if connect {
self.ws?.connect()
}
}
private func doFastUpgrade() {
if self.waitingForPoll {
NSLog("Outstanding poll when switched to websockets," +
"we'll probably disconnect soon. You should report this.")
}
self.sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
self._websocket = true
self._polling = false
self.fastUpgrade = false
self.probing = false
self.flushProbeWait()
}
private func doPoll() {
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
if self.websocket || self.waitingForPoll || !self.connected {
return
}
let req = NSURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
self.waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
self.doRequest(req)
}
private func doRequest(req:NSMutableURLRequest) {
if !self.polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
// NSLog("Doing request: \(req)")
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil {
if self!.polling {
self?.handlePollingFailed(err)
self?.handlePollingFailed(err.localizedDescription)
} else {
NSLog(err.localizedDescription)
}
return
}
// println(data)
// NSLog("Got response: \(res)")
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// println(str)
dispatch_async(self?.parseQueue) {[weak self] in
dispatch_async(self!.parseQueue) {
self?.parsePollingMessage(str)
return
}
}
self?.waitingForPoll = false
self?.doPoll()
if self!.fastUpgrade {
self?.doFastUpgrade()
return
} else if !self!.closed && self!.polling {
self?.doPoll()
}
}.resume()
}
private func flushProbeWait() {
// println("flushing probe wait")
// NSLog("flushing probe wait")
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
for waiter in self!.probeWait {
waiter()
self?.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self?.probeWait.removeAll(keepCapacity: false)
if self?.postWait.count != 0 {
self?.flushWaitingForPostToWebSocket()
}
}
}
private func flushWaitingForPost() {
if self.postWait.count == 0 || !self.connected {
return
@@ -198,399 +263,424 @@ class SocketEngine: NSObject, SRWebSocketDelegate {
self.flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in self.postWait {
let len = countElements(packet)
let len = count(packet)
postStr += "\(len):\(packet)"
}
self.postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
req.HTTPMethod = "POST"
req.setValue("application/html-text", forHTTPHeaderField: "Content-Type")
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
self.waitingForPost = true
// NSLog("posting: \(postStr)")
// NSLog("Posting with WS status of: \(self.websocket)")
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if err != nil {
if self!.polling {
self?.handlePollingFailed(err)
}
if self == nil {
return
} else if self == nil {
} else if err != nil && self!.polling {
self?.handlePollingFailed(err.localizedDescription)
return
} else if err != nil {
NSLog(err.localizedDescription)
return
}
self?.waitingForPost = false
dispatch_async(self!.emitQueue) {
self?.flushWaitingForPost()
self?.doPoll()
return
if !self!.fastUpgrade {
self?.flushWaitingForPost()
self?.doPoll()
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in self.postWait {
self.ws?.send(msg)
self.ws?.writeString(msg)
}
self.postWait.removeAll(keepCapacity: true)
}
// A poll failed, tell the client about it
// We check to see if we were closed by the server first
private func handlePollingFailed(reason:NSError?) {
if !self.client.reconnecting {
self.connected = false
self.ws?.close()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
self.client.pollingDidFail(reason)
private func handlePollingFailed(reason:String) {
self._connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
if self.client == nil {
return
}
if !self.closed && !self.client!.reconnecting {
self.client?.pollingDidFail(reason)
} else if !self.client!.reconnecting {
self.client?.didForceClose(reason)
}
}
func open(opts:[String: AnyObject]? = nil) {
if self.waitingForPost || self.waitingForPoll || self.websocket || self.connected {
assert(false, "We're in a bad state, this shouldn't happen.")
public func open(opts:[String: AnyObject]? = nil) {
if self.connected {
fatalError("Engine tried to open while connected")
}
let (urlPolling, urlWebSocket) = self.createURLs(params: opts)
self.closed = false
let (urlPolling, urlWebSocket) = self.createURLs(opts)
self.urlPolling = urlPolling
self.urlWebSocket = urlWebSocket
let reqPolling = NSURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
self.session.dataTaskWithRequest(reqPolling) {[weak self] data, res, err in
var err2:NSError?
if self == nil {
return
} else if err != nil || data == nil {
self?.handlePollingFailed(err)
return
}
if let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var mutString = RegexMutable(dataString)
let parsed:[String]? = mutString["(\\d*):(\\d)(\\{.*\\})?"].groups()
if parsed == nil || parsed?.count != 4 {
return
}
let length = parsed![1]
let type = parsed![2]
let jsonData = parsed![3].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if type != "0" {
NSLog("Error handshaking")
return
}
self?.connected = true
if let json = NSJSONSerialization.JSONObjectWithData(jsonData!,
options: NSJSONReadingOptions.AllowFragments, error: &err2) as? NSDictionary {
if let sid = json["sid"] as? String {
// println(json)
self?.sid = sid
if !self!.forcePolling {
self?.ws = SRWebSocket(URL:
NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
self?.ws?.delegate = self
self?.ws?.open()
}
} else {
NSLog("Error handshaking")
return
}
if let pingInterval = json["pingInterval"] as? Int {
self?.pingInterval = pingInterval / 1000
}
}
self?.doPoll()
self?.startPingTimer()
}}.resume()
if self.forceWebsockets {
self._polling = false
self._websocket = true
self.createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
reqPolling.allHTTPHeaderFields = headers
}
self.doRequest(reqPolling)
}
// Translatation of engine.io-parser#decodePayload
private func parsePollingMessage(str:String) {
if str.length == 1 {
return
}
// println(str)
let strArray = Array(str)
var length = ""
var n = 0
var msg = ""
func testLength(length:String, inout n:Int) -> Bool {
if let num = length.toInt() {
n = num
} else {
return true
}
return false
}
for var i = 0, l = str.length; i < l; i = i &+ 1 {
let chr = String(strArray[i])
if chr != ":" {
length += chr
} else {
if length == "" || testLength(length, &n) {
self.handlePollingFailed(nil)
NSLog("parsing error: \(str)")
self.handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i&+1...i&+n])
if let lengthInt = length.toInt() {
if lengthInt != msg.length {
println("parsing error")
NSLog("parsing error: \(str)")
return
}
}
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
fixSwift = msg
self?.parseEngineMessage(fixSwift)
self?.parseEngineMessage(msg, fromPolling: true)
return
}
}
i += n
length = ""
}
}
}
private func parseEngineMessage(message:AnyObject?) {
// println(message!)
if let data = message as? NSData {
// Strip off message type
self.client.parseSocketMessage(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
private func parseEngineData(data:NSData) {
if self.client == nil {
return
}
var messageString = message as String
var strMessage = RegexMutable(messageString)
// We should upgrade
if strMessage == "3probe" {
self.upgradeTransport()
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
return
}
let type = strMessage["^(\\d)"].groups()?[1]
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
// NSLog("Engine got message: \(message)")
if fromPolling {
fixDoubleUTF8(&message)
}
let type = message["^(\\d)"].groups()?[1]
if type != PacketType.MESSAGE.rawValue {
// TODO Handle other packets
if messageString.hasPrefix("b4") {
if message.hasPrefix("b4") {
// binary in base64 string
messageString.removeRange(Range<String.Index>(start: messageString.startIndex,
end: advance(messageString.startIndex, 2)))
if let data = NSData(base64EncodedString: messageString,
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
// println("sending \(data)")
self.client.parseSocketMessage(data)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
return
}
}
return
} else if type == PacketType.NOOP.rawValue {
self.doPoll()
return
}
if messageString == PacketType.CLOSE.rawValue {
// do nothing
} else if type == PacketType.PONG.rawValue {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
return
} else if type == PacketType.OPEN.rawValue {
var err:NSError?
message.removeAtIndex(message.startIndex)
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments, error: &err) as? NSDictionary {
if let sid = json["sid"] as? String {
// println(json)
self.sid = sid
self._connected = true
if !self.forcePolling && !self.forceWebsockets {
self.createWebsocket(andConnect: true)
}
} else {
NSLog("Error handshaking")
return
}
if let pingInterval = json["pingInterval"] as? Int {
self.pingInterval = pingInterval / 1000
}
} else {
fatalError("Error parsing engine connect")
}
self.startPingTimer()
if !self.forceWebsockets {
self.doPoll()
}
return
} else if type == PacketType.CLOSE.rawValue {
if self.client == nil {
return
}
if self.polling {
self.client!.didForceClose("Disconnect")
}
return
}
// println("Got something idk what to do with")
// println(messageString)
}
// Remove message type
messageString.removeAtIndex(messageString.startIndex)
// println("sending \(messageString)")
self.client.parseSocketMessage(messageString)
message.removeAtIndex(message.startIndex)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseSocketMessage(message)
return
}
}
private func probeWebSocket() {
if self.websocketConnected {
self.sendWebSocketMessage("probe", withType: PacketType.PING)
}
}
func send(msg:String, datas:[NSData]? = nil) {
let _send = {[weak self] (msg:String, datas:[NSData]?) -> () -> Void in
return {
if self == nil || !self!.connected {
return
}
if self!.websocket {
// println("sending ws: \(msg):\(datas)")
self?.sendWebSocketMessage(msg, withType: PacketType.MESSAGE, datas: datas)
} else {
// println("sending poll: \(msg):\(datas)")
self?.sendPollMessage(msg, withType: PacketType.MESSAGE, datas: datas)
}
}
}
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
if self!.probing {
self?.probeWait.append(_send(msg, datas))
} else {
_send(msg, datas)()
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if self.probing {
self.probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
self.write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
func sendPing() {
if self.websocket {
self.sendWebSocketMessage("", withType: PacketType.PING)
} else {
self.sendPollMessage("", withType: PacketType.PING)
}
self.write("", withType: PacketType.PING, withData: nil)
}
private func sendPollMessage(msg:String, withType type:PacketType, datas:[NSData]? = nil) {
// println("Sending: poll: \(msg) as type: \(type.rawValue)")
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
}
}
if waitingForPost {
self.doPoll()
return
} else {
self.flushWaitingForPost()
}
}
private func sendWebSocketMessage(str:String, withType type:PacketType, datas:[NSData]? = nil) {
// println("Sending: ws: \(str) as type: \(type.rawValue)")
self.ws?.send("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.send(data!)
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
// println("Sending poll: \(msg) as type: \(type.rawValue)")
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
}
}
}
if !self.waitingForPost {
self.flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
// println("Sending ws: \(str) as type: \(type.rawValue)")
self.ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.writeData(data!)
}
}
}
}
// Starts the ping timer
private func startPingTimer() {
if self.pingInterval == nil {
return
}
self.pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!), target: self,
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self.pingInterval!),
target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
private func upgradeTransport() {
if self.websocketConnected {
self.probing = false
self._websocket = true
self.waitingForPoll = false
self._polling = false
self.sendWebSocketMessage("", withType: PacketType.UPGRADE)
self.flushProbeWait()
// NSLog("Doing fast upgrade")
// Do a fast upgrade
// At this point, we should not send anymore polling messages-
self.fastUpgrade = true
self.sendPollMessage("", withType: PacketType.NOOP)
}
}
// Called when a message is recieved
func webSocket(webSocket:SRWebSocket!, didReceiveMessage message:AnyObject?) {
// println(message)
dispatch_async(self.handleQueue) {[weak self] in
self?.parseEngineMessage(message)
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
if self!.websocket {
// NSLog("writing ws: \(msg):\(data)")
self?.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
// NSLog("writing poll: \(msg):\(data)")
self?.sendPollMessage(msg, withType: type, datas: data)
}
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
if !self.forceWebsockets {
self.probing = true
self.probeWebSocket()
} else {
self._connected = true
self.probing = false
self._polling = false
}
}
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.closed {
self.client?.didForceClose("Disconnect")
return
}
}
// Called when the socket is opened
func webSocketDidOpen(webSocket:SRWebSocket!) {
self.websocketConnected = true
self.probing = true
self.probeWebSocket()
}
// Called when the socket is closed
func webSocket(webSocket:SRWebSocket!, didCloseWithCode code:Int, reason:String!, wasClean:Bool) {
self.websocketConnected = false
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self._connected = false
self._websocket = false
self._polling = true
self.client.webSocketDidCloseWithCode(code, reason: reason, wasClean: wasClean)
let reason = error?.localizedDescription
self.client?.webSocketDidCloseWithCode(1,
reason: reason == nil ? "Socket Disconnected" : reason!)
} else {
self.flushProbeWait()
}
}
// Called when an error occurs.
func webSocket(webSocket:SRWebSocket!, didFailWithError error:NSError!) {
self.websocketConnected = false
self._polling = true
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self.client.webSocketDidFailWithError(error)
} else {
self.flushProbeWait()
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text, fromPolling: false)
}
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
+41
View File
@@ -0,0 +1,41 @@
//
// SocketEngineClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/19/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 SocketEngineClient {
var handleQueue:dispatch_queue_attr_t! {get}
var emitQueue:dispatch_queue_attr_t! {get}
var reconnecting:Bool {get}
var socketURL:String {get}
var secure:Bool {get}
func didForceClose(reason:String)
func parseSocketMessage(msg:String)
func parseBinaryData(data:NSData)
func pollingDidFail(err:String)
func webSocketDidCloseWithCode(code:Int, reason:String)
func webSocketDidFailWithError(error:NSError)
}
-255
View File
@@ -1,255 +0,0 @@
//
// Event.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class SocketEvent {
let justAck:Bool!
var ack:Int?
var args:AnyObject!
lazy var currentPlace = 0
lazy var datas = [NSData]()
var event:String!
var placeholders:Int!
init(event:String, args:AnyObject?, placeholders:Int = 0, ackNum:Int? = nil, justAck:Bool = false) {
self.event = event
self.args = args
self.placeholders = placeholders
self.ack = ackNum
self.justAck = justAck
}
func addData(data:NSData) -> Bool {
func checkDoEvent() -> Bool {
if self.placeholders == self.currentPlace {
return true
} else {
return false
}
}
if checkDoEvent() {
return true
}
self.datas.append(data)
self.currentPlace++
if checkDoEvent() {
self.currentPlace = 0
return true
} else {
return false
}
}
class func createMessageForEvent(event:String, withArgs args:[AnyObject],
hasBinary:Bool, withDatas datas:Int = 0, toNamespace nsp:String?, wantsAck ack:Int? = nil) -> String {
var message:String
var jsonSendError:NSError?
if !hasBinary {
if nsp == nil {
if ack == nil {
message = "2[\"\(event)\""
} else {
message = "2\(ack!)[\"\(event)\""
}
} else {
if ack == nil {
message = "2/\(nsp!),[\"\(event)\""
} else {
message = "2/\(nsp!),\(ack!)[\"\(event)\""
}
}
} else {
if nsp == nil {
if ack == nil {
message = "5\(datas)-[\"\(event)\""
} else {
message = "5\(datas)-\(ack!)[\"\(event)\""
}
} else {
if ack == nil {
message = "5\(datas)-/\(nsp!),[\"\(event)\""
} else {
message = "5\(datas)-/\(nsp!),\(ack!)[\"\(event)\""
}
}
}
return self.completeMessage(message, args: args)
}
class func createAck(ack:Int, withArgs args:[AnyObject], withAckType ackType:Int,
withNsp nsp:String, withBinary binary:Int = 0) -> String {
var msg:String
if ackType == 3 {
if nsp == "/" {
msg = "3\(ack)["
} else {
msg = "3/\(nsp),\(ack)["
}
} else {
if nsp == "/" {
msg = "6\(binary)-\(ack)["
} else {
msg = "6\(binary)-/\(nsp),\(ack)["
}
}
return self.completeMessage(msg, args: args, ack: true)
}
private class func completeMessage(var message:String, args:[AnyObject], ack:Bool = false) -> String {
var err:NSError?
if args.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in args {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String
message += ","
continue
}
if arg is String {
message += "\"\(arg)\""
message += ","
continue
}
message += "\(arg)"
message += ","
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
private func fillInArray(arr:NSArray) -> NSArray {
var newArr = [AnyObject](count: arr.count, repeatedValue: 0)
// println(arr)
for i in 0..<arr.count {
if let nest = arr[i] as? NSArray {
newArr[i] = self.fillInArray(nest)
} else if let dict = arr[i] as? NSDictionary {
newArr[i] = self.fillInDict(dict)
} else if let str = arr[i] as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
newArr[i] = self.datas[num[1].toInt()!]
} else {
newArr[i] = arr[i]
}
} else {
newArr[i] = arr[i]
}
}
return newArr
}
private func fillInDict(dict:NSDictionary) -> NSDictionary {
var newDict = [String: AnyObject]()
for (key, value) in dict {
newDict[key as String] = value
// If the value is a string we need to check
// if it is a placeholder for data
if let str = value as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
newDict[key as String] = self.datas[num[1].toInt()!]
} else {
newDict[key as String] = str
}
} else if let nestDict = value as? NSDictionary {
newDict[key as String] = self.fillInDict(nestDict)
} else if let arr = value as? NSArray {
newDict[key as String] = self.fillInArray(arr)
}
}
return newDict
}
func fillInPlaceholders(_ args:AnyObject = true) -> AnyObject {
if let dict = args as? NSDictionary {
return self.fillInDict(dict)
} else if let arr = args as? NSArray {
return self.fillInArray(args as NSArray)
} else if let string = args as? String {
if string == "~~\(self.currentPlace)" {
return self.datas[0]
}
} else if args is Bool {
// We have multiple items
// Do it live
let argsAsArray = "[\(self.args)]"
if let parsedArr = SocketIOClient.parseData(argsAsArray) as? NSArray {
var returnArr = [AnyObject](count: parsedArr.count, repeatedValue: 0)
for i in 0..<parsedArr.count {
if let str = parsedArr[i] as? String {
let mut = RegexMutable(str)
if let num = mut["~~(\\d)"].groups() {
returnArr[i] = self.datas[num[1].toInt()!]
} else {
returnArr[i] = str
}
} else if let arr = parsedArr[i] as? NSArray {
returnArr[i] = self.fillInArray(arr)
} else if let dict = parsedArr[i] as? NSDictionary {
returnArr[i] = self.fillInDict(dict)
} else {
returnArr[i] = parsedArr[i]
}
}
return returnArr
}
}
return false
}
}
+9 -10
View File
@@ -22,16 +22,15 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
typealias AnyHandler = (event:String, items:AnyObject?)
typealias AckEmitter = (AnyObject...) -> Void
import Foundation
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int) -> AckEmitter {
func emitter(items:AnyObject...) {
socket.emitAck(num, withData: items, withAckType: type)
}
return emitter
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias AckEmitter = (AnyObject...) -> Void
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {
socket.emitAck(num, withData: items)
}
class SocketEventHandler {
@@ -46,7 +45,7 @@ class SocketEventHandler {
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!, type!) : nil)
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
return
}
}
+37
View File
@@ -0,0 +1,37 @@
//
// SocketFixUTF8.swift
// Socket.IO-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(inout name:String) {
let utf8 = name.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)!
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
}
File diff suppressed because it is too large. Load diff
+237
View File
@@ -0,0 +1,237 @@
//
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
enum SocketPacketType:Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init(str:String) {
if let int = str.toInt() {
self = SocketPacketType(rawValue: int)!
} else {
self = SocketPacketType(rawValue: 4)!
}
}
}
class SocketPacket {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:SocketPacketType?
init(type:SocketPacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
func checkDoEvent() -> Bool {
if self.placeholders == self.currentPlace {
return true
} else {
return false
}
}
if checkDoEvent() {
return true
}
self.binary.append(data)
self.currentPlace++
if checkDoEvent() {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
var message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = SocketPacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = SocketPacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
self.type = SocketPacketType.ACK
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
self.type = SocketPacketType.BINARY_ACK
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String
message += ","
continue
}
if arg is String {
message += "\"\(arg)\""
message += ","
continue
}
message += "\(arg)"
message += ","
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String {
if let num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
}
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
+259
View File
@@ -0,0 +1,259 @@
//
// SocketParser.swift
// Socket.IO-Swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class SocketParser {
private static let shredder = SocketParser.PacketShredder()
// Translation of socket.io-parser#deconstructPacket
private class PacketShredder {
var buf = ContiguousArray<NSData>()
func shred(data:AnyObject) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
return placeholder
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = shred(arr[i])
}
return newArr
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in newDict {
newDict[key as! NSCopying] = shred(value)
}
return newDict
} else {
return data
}
}
func deconstructPacket(packet:SocketPacket) {
if packet.data == nil {
return
}
var data = packet.data!
for i in 0..<data.count {
if data[i] is NSArray || data[i] is NSDictionary {
data[i] = shred(data[i])
} else if let bin = data[i] as? NSData {
data[i] = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
}
}
packet.data = data
packet.binary = buf
buf.removeAll(keepCapacity: true)
}
}
// Translation of socket.io-client#decodeString
class func parseString(str:String) -> SocketPacket? {
let arr = Array(str)
let type = String(arr[0])
if arr.count == 1 {
return SocketPacket(type: SocketPacketType(str: type))
}
var id = nil as Int?
var nsp = ""
var i = 0
var placeholders = -1
if type == "5" || type == "6" {
var buf = ""
while arr[++i] != "-" {
buf += String(arr[i])
if i == arr.count {
break
}
}
if buf.toInt() == nil || arr[i] != "-" {
NSLog("Error parsing \(str)")
return nil
} else {
placeholders = buf.toInt()!
}
}
if arr[i + 1] == "/" {
while ++i < arr.count {
let c = arr[i]
if c == "," {
break
}
nsp += String(c)
}
}
if i + 1 >= arr.count {
return SocketPacket(type: SocketPacketType(str: type),
nsp: nsp, placeholders: placeholders, id: id)
}
let next = String(arr[i + 1])
if next.toInt() != nil {
var c = ""
while ++i < arr.count {
if let int = String(arr[i]).toInt() {
c += String(arr[i])
} else {
--i
break
}
}
id = c.toInt()
}
if i + 1 < arr.count {
let d = String(arr[++i...arr.count-1])
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = SocketParser.parseData(noPlaceholders) as! [AnyObject]
return SocketPacket(type: SocketPacketType(str: type), data: data,
nsp: nsp, placeholders: placeholders, id: id)
}
return nil
}
// Parses data for events
class func parseData(data:String) -> AnyObject? {
var err:NSError?
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.AllowFragments, error: &err)
if err != nil {
// println(err)
return nil
}
return parsed
}
class func parseForEmit(packet:SocketPacket) {
shredder.deconstructPacket(packet)
}
// Parses messages recieved
class func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
if stringMessage == "" {
return
}
func checkNSP(nsp:String) -> Bool {
if nsp == "" && socket.nsp != "/" {
return true
} else {
return false
}
}
let p = parseString(stringMessage) as SocketPacket!
if p.type == SocketPacketType.EVENT {
if checkNSP(p.nsp) {
return
}
socket.handleEvent(p.getEvent(), data: p.data,
isInternalMessage: false, wantsAck: p.id)
} else if p.type == SocketPacketType.ACK {
if checkNSP(p.nsp) {
return
}
socket.handleAck(p.id!, data: p.data)
} else if p.type == SocketPacketType.BINARY_EVENT {
if checkNSP(p.nsp) {
return
}
socket.waitingData.append(p)
} else if p.type == SocketPacketType.BINARY_ACK {
if checkNSP(p.nsp) {
return
}
p.justAck = true
socket.waitingData.append(p)
} else if p.type == SocketPacketType.CONNECT {
if p.nsp == "" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
} else if p.type == SocketPacketType.DISCONNECT {
socket.didForceClose("Got Disconnect")
}
}
// Handles binary data
class func parseBinaryData(data:NSData, socket:SocketIOClient) {
// NSLog(data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros))
if socket.waitingData.count == 0 {
NSLog("Got data when not remaking packet")
return
}
let shouldExecute = socket.waitingData[0].addData(data)
if !shouldExecute {
return
}
let packet = socket.waitingData.removeAtIndex(0)
packet.fillInPlaceholders()
if !packet.justAck {
socket.handleEvent(packet.getEvent(), data: packet.data,
wantsAck: packet.id)
} else {
socket.handleAck(packet.id!, data: packet.data)
}
}
}
+80 -200
View File
@@ -16,11 +16,10 @@ import Foundation
var swiftRegexCache = [String: NSRegularExpression]()
public class SwiftRegex: NSObject, BooleanType {
var target: NSString
var target:String
var regex: NSRegularExpression
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
@@ -37,45 +36,45 @@ public class SwiftRegex: NSObject, BooleanType {
}
super.init()
}
class func failure(message: String) {
println("SwiftRegex: "+message)
//assert(false,"SwiftRegex: failed")
}
final var targetRange: NSRange {
return NSRange(location: 0,length: target.length)
return NSRange(location: 0,length: count(target.utf16))
}
final func substring(range: NSRange) -> NSString! {
final func substring(range: NSRange) -> String? {
if ( range.location != NSNotFound ) {
return target.substringWithRange(range)
return (target as NSString).substringWithRange(range)
} else {
return nil
}
}
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
return range(options: options).location != NSNotFound
}
public func range(options: NSMatchingOptions = nil) -> NSRange {
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
}
public func match(options: NSMatchingOptions = nil) -> String! {
return substring(range(options: options)) as String
public func match(options: NSMatchingOptions = nil) -> String? {
return substring(range(options: options))
}
public func groups(options: NSMatchingOptions = nil) -> [String]! {
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
public func groups(options: NSMatchingOptions = nil) -> [String]? {
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
}
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) as String! {
if let group = substring(match.rangeAtIndex(groupno)) {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
@@ -86,122 +85,83 @@ public class SwiftRegex: NSObject, BooleanType {
return nil
}
}
public subscript(groupno: Int) -> String! {
public subscript(groupno: Int) -> String? {
get {
return groups()[groupno]
return groups()?[groupno]
}
set(newValue) {
if let mutableTarget = target as? NSMutableString {
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult( match,
inString: target as String, offset: 0, template: newValue )
mutableTarget.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
}
} else {
SwiftRegex.failure("Group modify on non-mutable")
if newValue == nil {
return
}
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult(match,
inString: target as String, offset: 0, template: newValue!)
let mut = NSMutableString(string: target)
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
target = mut as String
}
}
}
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
as? [NSTextCheckingResult]
if matches != nil {
return matches!
} else {
return nil
}
}
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
return matchResults(options: options)!.map { $0.range }
}
public func matches(options: NSMatchingOptions = nil) -> [String] {
return matchResults(options: options)!.map( { self.substring($0.range) as String } )
return matchResults(options: options)!.map( { self.substring($0.range)!})
}
public func allGroups(options: NSMatchingOptions = nil) -> [[String]] {
return matchResults(options: options)!.map { self.groupsForMatch($0) }
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
return matchResults(options: options)!.map {self.groupsForMatch($0)}
}
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults(options: options)! {
out[substring(match.rangeAtIndex(1)) as String] =
substring(match.rangeAtIndex(2))
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
}
return out
}
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
options:NSMatchingOptions = nil) -> NSMutableString {
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
let matchRange = match.range
out.appendString( self.substring( NSRange(location:pos, length:matchRange.location-pos) ) as String )
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
out.appendString( substitution(match, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString( substring( NSRange(location:pos, length:targetRange.length-pos) ) as String )
if let mutableTarget = target as? NSMutableString {
mutableTarget.setString(out as String)
return mutableTarget
} else {
SwiftRegex.failure("Modify on non-mutable")
return out
}
out.appendString(substring( NSRange(location:pos, length:targetRange.length-pos))!)
return out as String
}
/* removed Beta6
public func __conversion() -> Bool {
return doesMatch()
}
public func __conversion() -> NSRange {
return range()
}
public func __conversion() -> String {
return match()
}
public func __conversion() -> [String] {
return matches()
}
public func __conversion() -> [[String]] {
return allGroups()
}
public func __conversion() -> [String:String] {
return dictionary()
}
*/
public var boolValue: Bool {
return doesMatch()
}
}
extension NSString {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
}
}
extension NSString {
public subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern)
}
}
extension String {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
@@ -214,116 +174,36 @@ extension String {
}
}
public func RegexMutable(string: NSString) -> NSMutableString {
return NSMutableString(string:string as String)
}
public func ~= (left: SwiftRegex, right: String) -> NSMutableString {
public func ~= (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: (String) -> String) -> NSMutableString {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range) as String)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]) -> String) -> NSMutableString {
public func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range)!)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: nil)
}
// my take on custom threading operators from
// http://ijoshsmith.com/2014/07/05/custom-threading-operator-in-swift/
private let _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
public func | (left: () -> Void, right: () -> Void) {
dispatch_async(_queue) {
left()
dispatch_async(dispatch_get_main_queue(), right)
}
}
public func | <R> (left: () -> R, right: (result:R) -> Void) {
dispatch_async(_queue) {
let result = left()
dispatch_async(dispatch_get_main_queue(), {
right(result:result)
})
}
}
// dispatch groups { block } & { block } | { completion }
public func & (left: () -> Void, right: () -> Void) -> [() -> Void] {
return [left, right];
}
public func & (left: [() -> Void], right: () -> Void) -> [() -> Void] {
var out = left
out.append( right )
return out
}
public func | (left: [() -> Void], right: () -> Void) {
let group = dispatch_group_create()
for block in left {
dispatch_group_async(group, _queue, block)
}
dispatch_group_notify(group, dispatch_get_main_queue(), right)
}
// parallel blocks with returns
public func & <R> (left: () -> R, right: () -> R) -> [() -> R] {
return [left, right]
}
public func & <R> (left: [() -> R], right: () -> R) -> [() -> R] {
var out = left
out.append( right )
return out
}
public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) {
let group = dispatch_group_create()
var results = Array<R!>()
for t in 0..<left.count {
results += [nil]
}
for t in 0..<left.count {
//dispatch_retain(group)
dispatch_group_enter(group)
dispatch_async(_queue, {
results[t] = left[t]()
dispatch_group_leave(group)
//dispatch_release(group)
})
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
right(results: results)
})
}, options: nil)
}
+713
View File
@@ -0,0 +1,713 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : UInt8 {
case ContinueFrame = 0x0
case TextFrame = 0x1
case BinaryFrame = 0x2
//3-7 are reserved.
case ConnectionClose = 0x8
case Ping = 0x9
case Pong = 0xA
//B-F reserved.
}
enum CloseCode : UInt16 {
case Normal = 1000
case GoingAway = 1001
case ProtocolError = 1002
case ProtocolUnhandledType = 1003
// 1004 reserved.
case NoStatusReceived = 1005
//1006 reserved.
case Encoding = 1007
case PolicyViolated = 1008
case MessageTooBig = 1009
}
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : Array<String>?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 2048
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var writeQueue: NSOperationQueue?
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
private var connectedBlock: ((Void) -> Void)? = nil
private var disconnectedBlock: ((NSError?) -> Void)? = nil
private var receivedTextBlock: ((String) -> Void)? = nil
private var receivedDataBlock: ((NSData) -> Void)? = nil
public var isConnected :Bool {
return connected
}
//init the websocket with a url
public init(url: NSURL) {
self.url = url
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
//closure based instead of the delegate
public convenience init(url: NSURL, protocols: Array<String>, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void), data:(NSData) -> Void) {
self.init(url: url, protocols: protocols)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
receivedDataBlock = data
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), text:((String) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedTextBlock = text
}
//same as above, just shorter
public convenience init(url: NSURL, connect:((Void) -> Void), disconnect:((NSError?) -> Void), data:((NSData) -> Void)) {
self.init(url: url)
connectedBlock = connect
disconnectedBlock = disconnect
receivedDataBlock = data
}
///Connect to the websocket server on a background thread
public func connect() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
self.createHTTPRequest()
})
}
///disconnect from the websocket server
public func disconnect() {
writeError(CloseCode.Normal.rawValue)
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let str: NSString = url.absoluteString!
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1)
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
}
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
self.addHeader(urlRequest, key: key, val: value)
}
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
self.initStreamsWithData(serializedRequest, Int(port!))
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest.takeUnretainedValue(),
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
}
if self.voipEnabled {
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if writeQueue != nil {
writeQueue!.waitUntilAllOperationsAreFinished()
}
inputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.close()
outputStream!.close()
inputStream = nil
outputStream = nil
isRunLoop = false
connected = false
dispatch_async(queue,{
if let disconnectBlock = self.disconnectedBlock {
disconnectBlock(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
connected = processHTTP(buffer, bufferLen: length)
if !connected {
dispatch_async(queue,{
//self.workaroundMethod()
let error = self.errorWithDetail("Invalid HTTP upgrade", code: 1)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
})
}
} else {
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if (fragBuffer != nil) {
var combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{
//self.workaroundMethod()
if let connectBlock = self.connectedBlock {
connectBlock()
}
self.delegate?.websocketDidConnect(self)
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0)
CFHTTPMessageAppendBytes(response.takeUnretainedValue(), buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response.takeUnretainedValue()) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
var response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
var offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].byteSwapped
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = UnsafePointer<UInt8>((buffer+offset))
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
let error = self.errorWithDetail("connection closed by server", code: code)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].byteSwapped
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].byteSwapped)
offset += sizeof(UInt16)
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = offset + Int(len)
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("first frame can't be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode)
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = offset + Int(len)
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{
if let textBlock = self.receivedTextBlock{
textBlock(str! as String)
}
self.delegate?.websocketDidReceiveMessage(self, text: str! as String)
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{
//self.workaroundMethod()
if let dataBlock = self.receivedDataBlock{
dataBlock(data)
}
self.delegate?.websocketDidReceiveData(self, data: data)
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.byteSwapped
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream in a
private func dequeueWrite(data: NSData, code: OpCode) {
if writeQueue == nil {
writeQueue = NSOperationQueue()
writeQueue!.maxConcurrentOperationCount = 1
}
writeQueue!.addOperationWithBlock {
//stream isn't ready, let's wait
var tries = 0;
while self.outputStream == nil || !self.connected {
if(tries < 5) {
sleep(1);
} else {
break;
}
tries++;
}
if !self.connected {
return
}
var offset = 2
UINT16_MAX
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = self.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).byteSwapped
offset += sizeof(UInt16)
} else {
buffer[1] = 127
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).byteSwapped
offset += sizeof(UInt64)
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if self.outputStream == nil {
break
}
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
if len == nil || len! < 0 {
var error: NSError?
if let streamError = self.outputStream?.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = self.errorWithDetail("output stream error during write", code: errCode)
}
if let disconnect = self.disconnectedBlock {
disconnect(error)
}
self.delegate?.websocketDidDisconnect(self, error: error)
break
} else {
total += len!
}
if total >= offset {
break
}
}
}
}
}