Compare commits

...
264 Commits
Author SHA1 Message Date
Erik 9bc40fcae1 bump version 2015-04-27 12:32:43 -04:00
Erik 1aa1a83cea Fix memory leak. Add reconnect method 2015-04-27 12:22:59 -04:00
Erik 8a23960e20 let the engine get the opts it needs 2015-04-27 10:34:23 -04:00
Erik a5b8202e45 fix socketio/socket.io-client-swift#66 2015-04-27 09:48:49 -04:00
Erik 918f176c56 fix socketio/socket.io-client-swift#65 2015-04-27 09:00:57 -04:00
Erik Little ef39651bfa Merge pull request #63 from socketio/engineclientcleanup
clean up engineclient
2015-04-25 11:16:13 -04:00
Erik e7f8f9db1a newline 2015-04-25 11:15:42 -04:00
Erik 0ccedfd0bf only emit error when there's actually an error 2015-04-25 10:48:23 -04:00
Erik 0416ecbaac clean up engineclient 2015-04-24 11:54:50 -04:00
Erik 21b295f8fa bump version 2015-04-23 14:30:40 -04:00
Erik a7fb0f847a Use the same name for objc/swift methods 2015-04-23 14:29:54 -04:00
Erik 27a767746b use new if let 2015-04-23 09:09:20 -04:00
Erik 59e068c853 tweaks 2015-04-23 07:11:22 -04:00
Erik 922ed4b575 fix socketio/socket.io-client-swift#61 2015-04-22 15:26:34 -04:00
Erik eab7311037 create write method that can be used from objc 2015-04-22 12:55:23 -04:00
Erik 7c0c12ba0c Merge branch 'yannickl-master' 2015-04-21 13:10:23 -04:00
Erik 306fc12cc5 Merge branch 'master' of https://github.com/yannickl/socket.io-client-swift into yannickl-master 2015-04-21 13:08:36 -04:00
Yannick Loriot 7f35e3e1e4 [FIX] memory leak with the takeUnretainedValue() 2015-04-21 18:57:36 +02:00
Erik cd48abe4cd bump version 2015-04-21 12:06:45 -04:00
Erik acfbcb6fe1 Merge branch 'master' of https://github.com/socketio/socket.io-client-swift 2015-04-21 12:03:52 -04:00
Erik 47f5dcbbcd style 2015-04-21 12:03:48 -04:00
Erik Little a161ed1756 Merge pull request #58 from yannickl/master
[FIX] Plus signs (+) is not URL encoded #57
2015-04-21 12:02:41 -04:00
Yannick Loriot 3fda340ad1 [FIX] Plus signs (+) is not URL encoded #57 2015-04-21 17:30:19 +02:00
Erik e33309827f actually use capture list 2015-04-20 15:18:08 -04:00
Erik 1753707bf8 don't use implicitly unwrapped engine 2015-04-20 13:54:16 -04:00
Erik cc99eae737 Add messages for socket/engine deinit 2015-04-20 12:42:35 -04:00
Erik 446cf57978 remove newline 2015-04-17 17:26:50 -04:00
Erik 80cee820a4 tweaks 2015-04-17 10:52:55 -04:00
Erik e4c2da515b clarify non-cocoapods installing 2015-04-17 10:19:22 -04:00
Erik bb4d285928 make note about required xcode version 2015-04-17 10:01:11 -04:00
Erik 5e5ec2f6b6 bump version 2015-04-17 07:57:34 -04:00
Erik 54aac236b8 update readme 2015-04-17 07:56:59 -04:00
Erik 8b05f922a6 rename socketackmap, code style changes for #55 2015-04-17 07:49:48 -04:00
Erik Little f38cf9ed3a Merge pull request #55 from ramki982/master
Adding support for self signed certificates by passing in a NSURLSessionDelegate optional
2015-04-17 07:44:23 -04:00
ramki982 057be73990 Uncommenting the string extension 2015-04-17 16:44:56 +05:30
ram ea3bd02f6a Adding a NSURLSessionDelegate to socket client options and in turn to socket engine to allow support for cases like self-signed certificates 2015-04-17 16:39:21 +05:30
Erik Little 06f04a046d Merge pull request #37 from redgreenapp/master
set cookie headers in doPoll and flushWaitingForPost
2015-04-16 16:59:02 -04:00
Matt Renaud ae27d93464 set cookie headers in doPoll and flushWaitingForPost 2015-04-16 16:48:06 -04:00
Erik 406504b09d tweaks 2015-04-16 14:27:19 -04:00
Erik 269bb5a943 tweaks 2015-04-15 09:48:03 -04:00
Erik 4be6b58150 async logging, simplify acks 2015-04-14 17:13:39 -04:00
Erik acefc89b0d tweaks 2015-04-14 16:25:08 -04:00
Erik 85e1f31538 bump version 2015-04-13 16:05:43 -04:00
Erik 8d9580900f don't force unwrap on making Engine.PacketType 2015-04-13 16:04:51 -04:00
Erik f87ed47723 tweak logging 2015-04-13 14:47:42 -04:00
Erik d887c96550 fix string becoming "nil" 2015-04-13 12:10:45 -04:00
Erik 6ec3861a4f refactor 2015-04-13 11:59:36 -04:00
Erik 43ec517156 work on a better output for socketpacket.description 2015-04-13 11:35:56 -04:00
Erik f67d3b23bb tweak emitack log message 2015-04-13 10:51:02 -04:00
Erik Little e6ecf34507 Merge pull request #53 from CallumOz/master
Fixed the use of the ?? operator because Swift is broken
2015-04-13 10:10:40 -04:00
Erik a1bab214b4 don't need to convert cstring 2015-04-13 10:09:53 -04:00
Callum Henshall 1c3ea76829 Fixed the use of the ?? operator because Swift is broken. 2015-04-13 15:35:01 +02:00
Erik 18928c823c bump version 2015-04-11 21:45:52 -04:00
Erik deac1bbe17 tweak logging 2015-04-11 21:45:01 -04:00
Erik 96fd2deb51 update README 2015-04-11 21:01:02 -04:00
Erik 69339cbb65 work on logging 2015-04-11 19:18:36 -04:00
Erik 7f7ae0b9f5 more tweaks 2015-04-11 10:51:56 -04:00
Erik 13718414da tweaks 2015-04-11 10:51:25 -04:00
Erik bfa967cc2a add gitignore 2015-04-10 12:03:48 -04:00
Erik a3e5824c22 update desc 2015-04-10 11:24:35 -04:00
Erik 96484e7622 upgrade desc 2015-04-10 00:01:59 -04:00
Erik 8205702afc bump version 2015-04-09 23:58:12 -04:00
Erik 156562902e rename folder 2015-04-09 19:09:53 -04:00
Erik 1334b973b9 tweak SocketPacket.PacketType 2015-04-09 13:20:01 -04:00
Erik 2a322ff5e5 Move SocketPacketType to SocketPacket.swift 2015-04-09 10:25:15 -04:00
Erik Little 20d1ad76af Update README.md 2015-04-09 10:19:02 -04:00
Erik 8fea5f25fd bump version 2015-04-09 09:23:16 -04:00
Erik 31e2f0ea4b clean up 2015-04-09 09:05:23 -04:00
Erik 7845251fc6 clean up 2015-04-09 01:47:28 -04:00
Erik 379912e280 Merge branch 'engineerrors' of https://github.com/nuclearace/Socket.IO-Client-Swift into engineerrors 2015-04-09 01:41:27 -04:00
Erik a9cf6885aa handle error message. Fix socketio/socket.io-client-swift#45 2015-04-09 01:40:12 -04:00
Erik 332ff6f40b handle error message 2015-04-09 01:39:27 -04:00
Erik 7adf624dca Merge branch 'master' into engineerrors 2015-04-09 01:14:40 -04:00
Erik ca4e404125 use static 2015-04-09 01:06:41 -04:00
Erik 67c41c0107 use new if let 2015-04-09 01:01:14 -04:00
Erik a01e85ba05 Merge branch 'master' into engineerrors 2015-04-09 00:39:43 -04:00
Erik 0588556c17 1.2 fixes single statement closures 2015-04-08 23:57:07 -04:00
Erik 076bbfc782 commit fix for binary 2015-04-08 21:51:11 -04:00
Erik 01e5e22e0b merge master 2015-04-08 21:16:56 -04:00
Erik 14487a1beb use int for enum 2015-04-08 21:14:52 -04:00
Erik eb5d03c88b redo types 2015-04-08 20:51:44 -04:00
Erik Little 903c578e75 Update README.md 2015-04-08 20:31:48 -04:00
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 be5764ce59 Merge branch 'master' into engineerrors 2015-04-07 21:54:59 -04:00
Erik ac28c7541e fix socketio/socket.io-client-swift#46 2015-04-07 21:53:14 -04:00
Erik c1eae5a500 fix missing file 2015-04-07 16:18:07 -04:00
Erik 473d422668 replace fatalError with an error method 2015-04-07 15:50:01 -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 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
21 changed files with 2627 additions and 2181 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
+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.
+108 -119
View File
@@ -1,137 +1,126 @@
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. 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 emit:@"echo" withItems:@[@"echo test"]];
[socket emitWithAck:@"ackack" withItems:@[@1]](10, ^(NSArray* data) {
NSLog(@"Got ack");
});
}];
[socket connect];
```
##Features
- Supports socket.io 1.0+
- Supports binary
- Supports Polling and WebSockets
- Supports TLS/SSL
- Can be used from Objective-C
##Installation
Requires Swift 1.2/Xcode 6.3
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
Manually (iOS 7+)
-----------------
1. Copy the SocketIOClientSwift folder into your Xcode project. (Make sure you add the files to your target(s))
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
CocoaPods 0.36.0 or later (iOS 8+)
------------------
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
```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.
- `log: Bool` If `true` socket will log debug messages. Default is false.
- `sessionDelegate: NSURLSessionDelegate` Sets an NSURLSessionDelegate for the underlying engine. Useful if you need to handle self-signed certs. Default is nil.
- `path: String` - If the server uses a custom path. ex: `"/swift"`. Default is `""`
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.emitObjc(event:String, args:[AnyObject])` - `emit` for Objective-C
5. `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.
6. `socket.emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler` - `emitWithAck` for Objective-C.
7. `socket.connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `socket.connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `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. `emit(event:String, withItems items:[AnyObject])` - `emit` for Objective-C
5. `emitWithAck(event:String, _ items:AnyObject...) -> (timeout:UInt64, callback:(NSArray?) -> Void) -> Void` - Sends a message that requests an acknowledgement from the server. Returns a function which you can use to add a handler. See example. Note: The message is not sent until you call the returned function.
6. `emitWithAck(event:String, withItems items:[AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void` - `emitWithAck` for Objective-C. Note: The message is not sent until you call the returned function.
7. `connect()` - Establishes a connection to the server. A "connect" event is fired upon successful connection.
8. `connectWithParams(params:[String: AnyObject])` - Establishes a connection to the server passing the specified params. A "connect" event is fired upon successful connection.
9. `close(#fast:Bool)` - Closes the socket. Once a socket is closed it should not be reopened. Pass true to fast if you're closing from a background task.
Events
------
1. `connect` - Emitted when on a successful connection.
2. `disconnect` - Emitted when the connection is closed.
3. `error` - Emitted if the websocket encounters an error.
3. `error` - Emitted on an error.
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("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"])
}
}
// Connecting
socket.connect()
// Sending binary
socket.emit("testData", [
"data": "Hello World".dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!,
"test": true])
```
Objective-C Example
===================
```objective-c
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8080" opts:nil];
[socket on: @"connect" callback: ^(NSArray* data, void (^ack)(NSArray*)) {
NSLog(@"connected");
[socket emitObjc:@"echo" :@[@"echo test"]];
[[socket emitWithAckObjc:@"ackack" :@[@"test"]] onAck:^(NSArray* data) {
NSLog(@"Got data");
}];
}];
```
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.2.0"
s.summary = "Socket.IO-client for iOS and OS X"
s.description = <<-DESC
Socket.IO-client for iOS and OS X.
Supports ws/wss/polling connections and binary.
For socket.io 1.0+ and Swift 1.2.
DESC
s.homepage = "https://github.com/socketio/socket.io-client-swift"
s.license = { :type => 'MIT' }
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.2.0' }
s.source_files = "SocketIOClientSwift/**/*.swift"
s.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
end
@@ -0,0 +1,74 @@
//
// SocketAckManager.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
private struct SocketAck: Hashable, Equatable {
let ack:Int
var callback:AckCallback!
var hashValue:Int {
return ack.hashValue
}
init(ack:Int) {
self.ack = ack
}
init(ack:Int, callback:AckCallback) {
self.ack = ack
self.callback = callback
}
}
private func <(lhs:SocketAck, rhs:SocketAck) -> Bool {
return lhs.ack < rhs.ack
}
private func ==(lhs:SocketAck, rhs:SocketAck) -> Bool {
return lhs.ack == rhs.ack
}
struct SocketAckManager {
private var acks = Set<SocketAck>(minimumCapacity: 1)
mutating func addAck(ack:Int, callback:AckCallback) {
self.acks.insert(SocketAck(ack: ack, callback: callback))
}
mutating func executeAck(ack:Int, items:[AnyObject]?) {
let callback = self.acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(items)
}
}
mutating func timeoutAck(ack:Int) {
let callback = self.acks.remove(SocketAck(ack: ack))
dispatch_async(dispatch_get_main_queue()) {
callback?.callback(["NO 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,26 +24,12 @@
import Foundation
public typealias AckCallback = (NSArray?) -> Void
@objc public class SocketAckHandler {
let ackNum:Int!
let event:String!
var callback:AckCallback?
@objc public final class SocketAnyEvent {
public let event:String!
public let items:NSArray?
init(event:String, ackNum:Int = 0) {
self.ackNum = ackNum
init(event:String, items:NSArray?) {
self.event = event
}
func onAck(callback:AckCallback) {
self.callback = callback
}
func executeAck(data:NSArray?) {
dispatch_async(dispatch_get_main_queue()) {[cb = self.callback] in
cb?(data)
return
}
self.items = items
}
}
+745
View File
@@ -0,0 +1,745 @@
//
// SocketEngine.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension String {
private var length:Int {
return count(self)
}
}
public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let session:NSURLSession!
private var closed = false
private var _connected = false
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var pingTimer:NSTimer?
private var postWait = [String]()
private var _polling = true
private var probing = false
private var probeWait = ProbeWaitQueue()
private var waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
let logType = "SocketEngine"
var connected:Bool {
return self._connected
}
weak var client:SocketEngineClient?
var cookies:[NSHTTPCookie]?
var log = false
var pingInterval:Int?
var polling:Bool {
return self._polling
}
var sid = ""
var socketPath = ""
var urlPolling:String?
var urlWebSocket:String?
var websocket:Bool {
return self._websocket
}
var ws:WebSocket?
public enum PacketType:Int {
case OPEN = 0
case CLOSE = 1
case PING = 2
case PONG = 3
case MESSAGE = 4
case UPGRADE = 5
case NOOP = 6
init?(str:String?) {
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
self = raw
} else {
return nil
}
}
}
public init(client:SocketEngineClient, sessionDelegate:NSURLSessionDelegate?) {
self.client = client
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: sessionDelegate, delegateQueue: self.workQueue)
}
public convenience init(client:SocketEngineClient, opts:NSDictionary?) {
self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate)
self.forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false
self.forcePolling = opts?["forcePolling"] as? Bool ?? false
self.cookies = opts?["cookies"] as? [NSHTTPCookie]
self.log = opts?["log"] as? Bool ?? false
self.socketPath = opts?["path"] as? String ?? ""
}
deinit {
SocketLogger.log("Engine is being deinit", client: self)
}
public func close(#fast:Bool) {
SocketLogger.log("Engine is being closed. Fast: \(fast)", client: self)
self.pingTimer?.invalidate()
self.closed = true
self.write("", withType: PacketType.CLOSE, withData: nil)
self.ws?.disconnect()
self.stopPolling()
if fast || self.polling {
self.client?.engineDidClose("Disconnect")
}
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if self.websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return (mutData, nil)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]?) -> (String, String) {
if self.client == nil {
return ("", "")
}
var url = "\(self.client!.socketURL)\(self.socketPath)/socket.io/?transport="
var urlPolling:String
var urlWebSocket:String
if self.client!.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" ").invertedSet
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocket(andConnect connect:Bool) {
self.ws = WebSocket(url: NSURL(string: self.urlWebSocket! + "&sid=\(self.sid)")!,
cookies: self.cookies)
self.ws?.queue = self.handleQueue
self.ws?.delegate = self
if connect {
self.ws?.connect()
}
}
private func doFastUpgrade() {
if self.waitingForPoll {
SocketLogger.err("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", client: self)
}
self.sendWebSocketMessage("", withType: PacketType.UPGRADE, datas: nil)
self._websocket = true
self._polling = false
self.fastUpgrade = false
self.probing = false
self.flushProbeWait()
}
private func doPoll() {
if self.websocket || self.waitingForPoll || !self.connected {
return
}
self.waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
self.doRequest(req)
}
private func doRequest(req:NSMutableURLRequest) {
if !self.polling {
return
}
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
SocketLogger.log("Doing polling request", client: self)
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil {
if self!.polling {
self?.handlePollingFailed(err.localizedDescription)
} else {
NSLog(err.localizedDescription)
}
return
}
SocketLogger.log("Got polling response", client: self!)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(self!.parseQueue) {[weak self] in
self?.parsePollingMessage(str)
}
}
self?.waitingForPoll = false
if self!.fastUpgrade {
self?.doFastUpgrade()
return
} else if !self!.closed && self!.polling {
self?.doPoll()
}}.resume()
}
private func flushProbeWait() {
SocketLogger.log("Flushing probe wait", client: self)
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
for waiter in self!.probeWait {
self?.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self?.probeWait.removeAll(keepCapacity: false)
if self?.postWait.count != 0 {
self?.flushWaitingForPostToWebSocket()
}
}
}
private func flushWaitingForPost() {
if self.postWait.count == 0 || !self.connected {
return
} else if self.websocket {
self.flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in self.postWait {
let len = count(packet)
postStr += "\(len):\(packet)"
}
self.postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
self.waitingForPost = true
SocketLogger.log("POSTing: \(postStr)", client: self)
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil && self!.polling {
self?.handlePollingFailed(err.localizedDescription)
return
} else if err != nil {
NSLog(err.localizedDescription)
return
}
self?.waitingForPost = false
dispatch_async(self!.emitQueue) {[weak self] in
if !self!.fastUpgrade {
self?.flushWaitingForPost()
self?.doPoll()
}
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in self.postWait {
self.ws?.writeString(msg)
}
self.postWait.removeAll(keepCapacity: true)
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
self._connected = false
self.ws?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
// If cancelled we were already closing
if self.client == nil || reason == "cancelled" {
return
}
if !self.closed {
self.client?.didError(reason)
self.client?.engineDidClose(reason)
}
}
public func open(opts:[String: AnyObject]? = nil) {
if self.connected {
SocketLogger.err("Tried to open while connected", client: self)
self.client?.didError("Tried to open while connected")
return
}
SocketLogger.log("Starting engine", client: self)
SocketLogger.log("Handshaking", client: self)
self.closed = false
let (urlPolling, urlWebSocket) = self.createURLs(opts)
self.urlPolling = urlPolling
self.urlWebSocket = urlWebSocket
if self.forceWebsockets {
self._polling = false
self._websocket = true
self.createWebsocket(andConnect: true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
reqPolling.allHTTPHeaderFields = headers
}
self.doRequest(reqPolling)
}
// Translatation of engine.io-parser#decodePayload
private func parsePollingMessage(str:String) {
if str.length == 1 {
return
}
// println(str)
let strArray = Array(str)
var length = ""
var n = 0
var msg = ""
func testLength(length:String, inout n:Int) -> Bool {
if let num = length.toInt() {
n = num
return false
} else {
return true
}
}
for var i = 0, l = str.length; i < l; i = i &+ 1 {
let chr = String(strArray[i])
if chr != ":" {
length += chr
} else {
if length == "" || testLength(length, &n) {
SocketLogger.err("Parsing error: \(str)", client: self)
self.handlePollingFailed("Error parsing XHR message")
return
}
msg = String(strArray[i&+1...i&+n])
if let lengthInt = length.toInt() {
if lengthInt != msg.length {
SocketLogger.err("parsing error: \(str)", client: self)
return
}
}
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
self?.parseEngineMessage(msg, fromPolling: true)
}
}
i += n
length = ""
}
}
}
private func parseEngineData(data:NSData) {
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
}
private func parseEngineMessage(var message:String, fromPolling:Bool) {
SocketLogger.log("Got message: \(message)", client: self)
if fromPolling {
fixDoubleUTF8(&message)
}
let type = PacketType(str: (message["^(\\d)"].groups()?[1]))
if type == PacketType.MESSAGE {
// Remove message type
message.removeAtIndex(message.startIndex)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseSocketMessage(message)
}
} else if type == PacketType.NOOP {
self.doPoll()
return
} else if type == PacketType.PONG {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
return
} else if type == PacketType.OPEN {
var err:NSError?
message.removeAtIndex(message.startIndex)
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments,
error: &err) as? NSDictionary, let sid = json["sid"] as? String {
self.sid = sid
self._connected = true
if !self.forcePolling && !self.forceWebsockets {
self.createWebsocket(andConnect: true)
}
if let pingInterval = json["pingInterval"] as? Int {
self.pingInterval = pingInterval / 1000
}
} else {
self.client?.didError("Engine failed to handshake")
return
}
self.startPingTimer()
if !self.forceWebsockets {
self.doPoll()
}
return
} else if type == PacketType.CLOSE {
if self.client == nil {
return
}
if self.polling {
self.client!.engineDidClose("Disconnect")
}
return
} else if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
where self.client != nil {
// println("sending \(data)")
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
}
}
}
}
private func probeWebSocket() {
if self.websocketConnected {
self.sendWebSocketMessage("probe", withType: PacketType.PING)
}
}
/// Send an engine message (4)
public func send(msg:String, withData datas:ContiguousArray<NSData>?) {
if self.probing {
self.probeWait.append((msg, PacketType.MESSAGE, datas))
} else {
self.write(msg, withType: PacketType.MESSAGE, withData: datas)
}
}
func sendPing() {
self.write("", withType: PacketType.PING, withData: nil)
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending poll: \(msg) as type: \(type.rawValue)", client: self)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
self.postWait.append(strMsg)
if datas != nil {
for data in datas! {
let (nilData, b64Data) = self.createBinaryDataForSend(data)
self.postWait.append(b64Data!)
}
}
if !self.waitingForPost {
self.flushWaitingForPost()
}
}
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str:String, withType type:PacketType,
datas:ContiguousArray<NSData>? = nil) {
SocketLogger.log("Sending ws: \(str) as type: \(type.rawValue)", client: self)
self.ws?.writeString("\(type.rawValue)\(str)")
if datas != nil {
for data in datas! {
let (data, nilString) = self.createBinaryDataForSend(data)
if data != nil {
self.ws?.writeData(data!)
}
}
}
}
// Starts the ping timer
private func startPingTimer() {
if self.pingInterval == nil {
return
}
self.pingTimer?.invalidate()
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.pingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(self!.pingInterval!),
target: self!,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
func stopPolling() {
self.session.invalidateAndCancel()
}
private func upgradeTransport() {
if self.websocketConnected {
SocketLogger.log("Upgrading transport to WebSockets", client: self)
// Do a fast upgrade
// At this point, we should not send anymore polling messages-
self.fastUpgrade = true
self.sendPollMessage("", withType: PacketType.NOOP)
}
}
/**
Write a message, independent of transport.
*/
public func write(msg:String, withType type:PacketType, withData data:ContiguousArray<NSData>?) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
if self!.websocket {
SocketLogger.log("Writing ws: \(msg):\(data)", client: self!)
self?.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
SocketLogger.log("Writing poll: \(msg):\(data)", client: self!)
self?.sendPollMessage(msg, withType: type, datas: data)
}
}
}
/**
Write a message, independent of transport. For Objective-C. withData should be an NSArray of NSData
*/
public func writeObjc(msg:String, withType type:Int, withData data:NSArray?) {
if let pType = PacketType(rawValue: type) {
var arr = ContiguousArray<NSData>()
if data != nil {
for d in data! {
arr.append(d as! NSData)
}
}
self.write(msg, withType: pType, withData: arr)
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
if !self.forceWebsockets {
self.probing = true
self.probeWebSocket()
} else {
self._connected = true
self.probing = false
self._polling = false
}
}
public func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.closed {
self.client?.engineDidClose("Disconnect")
return
}
if self.websocket {
self.pingTimer?.invalidate()
self._connected = false
self._websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
self.client?.didError(reason)
}
self.client?.engineDidClose(reason)
} else {
self.flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
@@ -0,0 +1,38 @@
//
// 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 socketURL:String {get}
var secure:Bool {get}
func didError(reason:AnyObject)
func engineDidClose(reason:String)
func parseSocketMessage(msg:String)
func parseBinaryData(data:NSData)
}
@@ -24,19 +24,13 @@
import Foundation
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias AnyHandler = (event:String, items:AnyObject?)
public typealias AckEmitter = (AnyObject...) -> Void
private func emitAckCallback(socket:SocketIOClient, num:Int, type:Int) -> AckEmitter {
func emitter(items:AnyObject...) {
socket.emitAck(num, withData: items, withAckType: type)
}
return emitter
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {
socket.emitAck(num, withData: items)
}
class SocketEventHandler {
final class SocketEventHandler {
let event:String!
let callback:NormalCallback?
@@ -48,8 +42,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)
return
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
}
}
}
+38
View File
@@ -0,0 +1,38 @@
//
// 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)!
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
}
+507
View File
@@ -0,0 +1,507 @@
//
// SocketIOClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 11/23/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient {
private lazy var params = [String: AnyObject]()
private var anyHandler:((SocketAnyEvent) -> Void)?
private var _closed = false
private var _connected = false
private var _connecting = false
private var currentReconnectAttempt = 0
private var handlers = ContiguousArray<SocketEventHandler>()
private var paramConnect = false
private var _secure = false
private var _sid:String?
private var _reconnecting = false
private var reconnectTimer:NSTimer?
let reconnectAttempts:Int!
let logType = "SocketClient"
var ackHandlers = SocketAckManager()
var currentAck = -1
var log = false
var waitingData = ContiguousArray<SocketPacket>()
var sessionDelegate:NSURLSessionDelegate?
public let socketURL:String
public let handleAckQueue = dispatch_queue_create("handleAckQueue", DISPATCH_QUEUE_SERIAL)
public let handleQueue = dispatch_queue_create("handleQueue", DISPATCH_QUEUE_SERIAL)
public let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
public var closed:Bool {
return self._closed
}
public var connected:Bool {
return self._connected
}
public var connecting:Bool {
return self._connecting
}
public var engine:SocketEngine?
public var nsp = "/"
public var opts:[String: AnyObject]?
public var reconnects = true
public var reconnecting:Bool {
return self._reconnecting
}
public var reconnectWait = 10
public var secure:Bool {
return self._secure
}
public var sid:String? {
return self._sid
}
/**
Create a new SocketIOClient. opts can be omitted
*/
public init(var socketURL:String, opts:[String: AnyObject]? = nil) {
if socketURL["https://"].matches().count != 0 {
self._secure = true
}
socketURL = socketURL["http://"] ~= ""
socketURL = socketURL["https://"] ~= ""
self.socketURL = socketURL
self.opts = opts
// Set options
if opts != nil {
if let sessionDelegate = opts!["sessionDelegate"] as? NSURLSessionDelegate {
self.sessionDelegate = sessionDelegate
}
if let log = opts!["log"] as? Bool {
self.log = log
}
if var nsp = opts!["nsp"] as? String {
if nsp != "/" && nsp.hasPrefix("/") {
nsp.removeAtIndex(nsp.startIndex)
}
self.nsp = nsp
}
if let reconnects = opts!["reconnects"] as? Bool {
self.reconnects = reconnects
}
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts!["reconnectWait"] as? Int {
self.reconnectWait = abs(reconnectWait)
}
} else {
self.reconnectAttempts = -1
}
super.init()
}
public convenience init(socketURL:String, options:[String: AnyObject]?) {
self.init(socketURL: socketURL, opts: options)
}
deinit {
SocketLogger.log("Client is being deinit", client: self)
}
private func addEngine() {
SocketLogger.log("Adding engine", client: self)
self.engine = SocketEngine(client: self, opts: self.opts)
}
/**
Closes the socket. Only reopen the same socket if you know what you're doing.
Will turn off automatic reconnects.
Pass true to fast if you're closing from a background task
*/
public func close(#fast:Bool) {
SocketLogger.log("Closing socket", client: self)
self.reconnects = false
self._connecting = false
self._connected = false
self._reconnecting = false
self.engine?.close(fast: fast)
self.engine = nil
}
/**
Connect to the server.
*/
public func connect() {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
if self.connected {
return
}
self.addEngine()
self.engine?.open()
}
/**
Connect to the server with params that will be passed on connection.
*/
public func connectWithParams(params:[String: AnyObject]) {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
if self.connected {
return
}
self.params = params
self.paramConnect = true
self.addEngine()
self.engine?.open(opts: params)
}
private func createOnAck(event:String, items:[AnyObject]) -> OnAckCallback {
return {[weak self, ack = ++self.currentAck] timeout, callback in
if self == nil {
return
}
self?.ackHandlers.addAck(ack, callback: callback)
dispatch_async(self!.emitQueue) {
self?._emit(event, items, ack: ack)
}
if timeout != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
self?.ackHandlers.timeoutAck(ack)
}
}
}
}
func didConnect() {
SocketLogger.log("Socket connected", client: self)
self._closed = false
self._connected = true
self._connecting = false
self._reconnecting = false
self.currentReconnectAttempt = 0
self.reconnectTimer?.invalidate()
self.reconnectTimer = nil
self._sid = self.engine?.sid
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.handleEvent("connect", data: nil, isInternalMessage: false)
}
func didDisconnect(reason:String) {
if self.closed {
return
}
SocketLogger.log("Disconnected: \(reason)", client: self)
self._closed = true
self._connected = false
self.reconnects = false
self._connecting = false
self._reconnecting = false
// Make sure the engine is actually dead.
self.engine?.close(fast: true)
self.handleEvent("disconnect", data: [reason], isInternalMessage: true)
}
/// error
public func didError(reason:AnyObject) {
SocketLogger.err("Error: \(reason)", client: self)
self.handleEvent("error", data: reason as? [AnyObject] ?? [reason],
isInternalMessage: true)
}
/**
Same as close
*/
public func disconnect(#fast:Bool) {
self.close(fast: fast)
}
/**
Send a message to the server
*/
public func emit(event:String, _ items:AnyObject...) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
Same as emit, but meant for Objective-C
*/
public func emit(event:String, withItems items:[AnyObject]) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, items)
}
}
/**
Sends a message to the server, requesting an ack. Use the onAck method of SocketAckHandler to add
an ack.
*/
public func emitWithAck(event:String, _ items:AnyObject...) -> OnAckCallback {
if !self.connected {
return createOnAck(event, items: items)
}
return self.createOnAck(event, items: items)
}
/**
Same as emitWithAck, but for Objective-C
*/
public func emitWithAck(event:String, withItems items:[AnyObject]) -> OnAckCallback {
if !self.connected {
return self.createOnAck(event, items: items)
}
return self.createOnAck(event, items: items)
}
private func _emit(event:String, _ args:[AnyObject], ack:Int? = nil) {
if !self.connected {
return
}
let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createMessageForEvent(event)
SocketLogger.log("Emitting: \(str)", client: self)
if packet.type == SocketPacket.PacketType.BINARY_EVENT {
self.engine?.send(str, withData: packet.binary)
} else {
self.engine?.send(str, withData: nil)
}
}
// If the server wants to know that the client received data
func emitAck(ack:Int, withData args:[AnyObject]) {
dispatch_async(self.emitQueue) {[weak self] in
if self == nil || !self!.connected {
return
}
let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack)
let str:String
SocketParser.parseForEmit(packet)
str = packet.createAck()
SocketLogger.log("Emitting Ack: \(str)", client: self!)
if packet.type == SocketPacket.PacketType.BINARY_ACK {
self?.engine?.send(str, withData: packet.binary)
} else {
self?.engine?.send(str, withData: nil)
}
}
}
public func engineDidClose(reason:String) {
self._connected = false
self._connecting = false
if self.closed || !self.reconnects {
self.didDisconnect("Engine closed")
} else if !self.reconnecting {
self.handleEvent("reconnect", data: [reason], isInternalMessage: true)
self.tryReconnect()
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack:Int, data:AnyObject?) {
SocketLogger.log("Handling ack: \(ack) with data: \(data)", client: self)
self.ackHandlers.executeAck(ack,
items: (data as? [AnyObject]?) ?? (data != nil ? [data!] : nil))
}
/**
Causes an event to be handled. Only use if you know what you're doing.
*/
public func handleEvent(event:String, data:[AnyObject]?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil) {
// println("Should do event: \(event) with data: \(data)")
if !self.connected && !isInternalMessage {
return
}
SocketLogger.log("Handling event: \(event) with data: \(data)", client: self)
if self.anyHandler != nil {
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.anyHandler?(SocketAnyEvent(event: event, items: data))
}
}
for handler in self.handlers {
if handler.event == event {
if ack != nil {
handler.executeCallback(data, withAck: ack!, withSocket: self)
} else {
handler.executeCallback(data)
}
}
}
}
func joinNamespace() {
SocketLogger.log("Joining namespace", client: self)
if self.nsp != "/" {
self.engine?.send("0/\(self.nsp)", withData: nil)
}
}
/**
Removes handler(s)
*/
public func off(event:String) {
SocketLogger.log("Removing handler for event: \(event)", client: self)
self.handlers = self.handlers.filter {$0.event == event ? false : true}
}
/**
Adds a handler for an event.
*/
public func on(name:String, callback:NormalCallback) {
SocketLogger.log("Adding handler for event: \(name)", client: self)
let handler = SocketEventHandler(event: name, callback: callback)
self.handlers.append(handler)
}
/**
Adds a handler that will be called on every event.
*/
public func onAny(handler:(SocketAnyEvent) -> Void) {
self.anyHandler = handler
}
/**
Same as connect
*/
public func open() {
self.connect()
}
public func parseSocketMessage(msg:String) {
SocketParser.parseSocketMessage(msg, socket: self)
}
public func parseBinaryData(data:NSData) {
SocketParser.parseBinaryData(data, socket: self)
}
/**
Trieds to reconnect to the server.
*/
public func reconnect() {
self._connected = false
self._connecting = false
self._reconnecting = false
self.engine?.stopPolling()
self.tryReconnect()
}
// We lost connection and should attempt to reestablish
@objc private func tryReconnect() {
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
self.didDisconnect("Reconnect Failed")
return
} else if self.connected {
self._connecting = false
self._reconnecting = false
return
}
if self.reconnectTimer == nil {
SocketLogger.log("Starting reconnect", client: self)
self._reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
}
}
SocketLogger.log("Trying to reconnect", client: self)
self.handleEvent("reconnectAttempt", data: [self.reconnectAttempts - self.currentReconnectAttempt],
isInternalMessage: true)
self.currentReconnectAttempt++
if self.paramConnect {
self.connectWithParams(self.params)
} else {
self.connect()
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//
// SocketLogger.swift
// SocketIO-Swift
//
// Created by Erik Little on 4/11/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol SocketLogClient {
var log:Bool {get set}
var logType:String {get}
}
final class SocketLogger {
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
static func log(message:String, client:SocketLogClient, altType:String? = nil) {
if !client.log {
return
}
dispatch_async(printQueue) {[type = client.logType] in
NSLog("%@: %@", altType ?? type, message)
}
}
static func err(message:String, client:SocketLogClient, altType:String? = nil) {
if !client.log {
return
}
dispatch_async(printQueue) {[type = client.logType] in
NSLog("ERROR %@: %@", altType ?? type, message)
}
}
}
+233
View File
@@ -0,0 +1,233 @@
//
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
final class SocketPacket: Printable {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var description:String {
var better = "SocketPacket {type: ~~0; data: ~~1; " +
"id: ~~2; placeholders: ~~3;}"
better = better["~~0"] ~= (self.type != nil ? String(self.type!.rawValue) : "nil")
better = better["~~1"] ~= (self.data != nil ? "\(self.data!)" : "nil")
better = better["~~2"] ~= (self.id != nil ? String(self.id!) : "nil")
better = better["~~3"] ~= (self.placeholders != nil ? String(self.placeholders!) : "nil")
return better
}
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:PacketType?
enum PacketType:Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init?(str:String) {
if let int = str.toInt(), raw = PacketType(rawValue: int) {
self = raw
} else {
return nil
}
}
}
init(type:PacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
if self.placeholders == self.currentPlace {
return true
}
self.binary.append(data)
self.currentPlace++
if self.placeholders == self.currentPlace {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
let message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = PacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = PacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
self.type = PacketType.ACK
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
self.type = PacketType.BINARY_ACK
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String + ","
} else if arg is String {
message += "\"\(arg)\","
} else if arg is NSNull {
message += "null,"
} else {
message += "\(arg),"
}
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String, num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
+267
View File
@@ -0,0 +1,267 @@
//
// SocketParser.swift
// Socket.IO-Swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class SocketParser {
private static let shredder = SocketParser.PacketShredder()
// Translation of socket.io-parser#deconstructPacket
private final class PacketShredder {
var buf = ContiguousArray<NSData>()
func shred(data:AnyObject) -> AnyObject {
if let bin = data as? NSData {
let placeholder = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
return placeholder
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = shred(arr[i])
}
return newArr
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in newDict {
newDict[key as! NSCopying] = shred(value)
}
return newDict
} else {
return data
}
}
func deconstructPacket(packet:SocketPacket) {
if packet.data == nil {
return
}
var data = packet.data!
for i in 0..<data.count {
if data[i] is NSArray || data[i] is NSDictionary {
data[i] = shred(data[i])
} else if let bin = data[i] as? NSData {
data[i] = ["_placeholder" :true, "num": buf.count]
buf.append(bin)
}
}
packet.data = data
packet.binary = buf
buf.removeAll(keepCapacity: true)
}
}
// Translation of socket.io-client#decodeString
static func parseString(str:String) -> SocketPacket? {
let arr = Array(str)
let type = String(arr[0])
if arr.count == 1 {
return SocketPacket(type: SocketPacket.PacketType(str: type))
}
var id = nil as Int?
var nsp = ""
var i = 0
var placeholders = -1
if type == "5" || type == "6" {
var buf = ""
while arr[++i] != "-" {
buf += String(arr[i])
if i == arr.count {
break
}
}
if let holders = buf.toInt() where arr[i] == "-" {
placeholders = holders
} else {
NSLog("Error parsing \(str)")
return nil
}
}
if arr[i + 1] == "/" {
while ++i < arr.count {
let c = arr[i]
if c == "," {
break
}
nsp += String(c)
}
}
if i + 1 >= arr.count {
return SocketPacket(type: SocketPacket.PacketType(str: type),
nsp: nsp, placeholders: placeholders, id: id)
}
let next = String(arr[i + 1])
if next.toInt() != nil {
var c = ""
while ++i < arr.count {
if let int = String(arr[i]).toInt() {
c += String(arr[i])
} else {
--i
break
}
}
id = c.toInt()
}
if ++i < arr.count {
let d = String(arr[i...arr.count-1])
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
let data = SocketParser.parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
return SocketPacket(type: SocketPacket.PacketType(str: type), data: data,
nsp: nsp, placeholders: placeholders, id: id)
}
return nil
}
// Parses data for events
static func parseData(data:String) -> AnyObject? {
var err:NSError?
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
options: NSJSONReadingOptions.AllowFragments, error: &err)
if err != nil {
// println(err)
return nil
}
return parsed
}
static func parseForEmit(packet:SocketPacket) {
shredder.deconstructPacket(packet)
}
// Parses messages recieved
static func parseSocketMessage(stringMessage:String, socket:SocketIOClient) {
if stringMessage == "" {
return
}
func checkNSP(nsp:String) -> Bool {
return nsp == "" && socket.nsp != "/"
}
SocketLogger.log("Parsing \(stringMessage)", client: socket, altType: "SocketParser")
let p:SocketPacket
if let pack = parseString(stringMessage) {
p = pack
} else {
socket.didError("Error parsing packet")
return
}
// Don't call SocketPacket.description unless we need to
if socket.log {
SocketLogger.log("Decoded packet as: \(p)", client: socket, altType: "SocketParser")
}
if p.type == SocketPacket.PacketType.EVENT {
if checkNSP(p.nsp) {
return
}
socket.handleEvent(p.getEvent(), data: p.data,
isInternalMessage: false, wantsAck: p.id)
} else if p.type == SocketPacket.PacketType.ACK {
if checkNSP(p.nsp) {
return
}
socket.handleAck(p.id!, data: p.data)
} else if p.type == SocketPacket.PacketType.BINARY_EVENT {
if checkNSP(p.nsp) {
return
}
socket.waitingData.append(p)
} else if p.type == SocketPacket.PacketType.BINARY_ACK {
if checkNSP(p.nsp) {
return
}
p.justAck = true
socket.waitingData.append(p)
} else if p.type == SocketPacket.PacketType.CONNECT {
if p.nsp == "" && socket.nsp != "/" {
socket.joinNamespace()
} else if p.nsp != "" && socket.nsp == "/" {
socket.didConnect()
} else {
socket.didConnect()
}
} else if p.type == SocketPacket.PacketType.DISCONNECT {
socket.didDisconnect("Got Disconnect")
} else if p.type == SocketPacket.PacketType.ERROR {
socket.didError(p.data == nil ? "Error" : p.data!)
}
}
static func parseBinaryData(data:NSData, socket:SocketIOClient) {
if socket.waitingData.count == 0 {
SocketLogger.err("Got data when not remaking packet", client: socket, altType: "SocketParser")
return
}
let shouldExecute = socket.waitingData[0].addData(data)
if !shouldExecute {
return
}
let packet = socket.waitingData.removeAtIndex(0)
packet.fillInPlaceholders()
if !packet.justAck {
socket.handleEvent(packet.getEvent(), data: packet.data,
wantsAck: packet.id)
} else {
socket.handleAck(packet.id!, data: packet.data)
}
}
}
+34
View File
@@ -0,0 +1,34 @@
//
// SocketTypes.swift
// SocketIO-Swift
//
// Created by Erik Little on 4/8/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// @objc_block is undocumented, but is used because Swift assumes that all
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
// And the way things are done here, the bridging fails to copy the block in
// SocketAckMap#addAck
public typealias AckCallback = @objc_block (NSArray?) -> Void
public typealias AckEmitter = (AnyObject...) -> Void
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
+209
View File
@@ -0,0 +1,209 @@
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by John Holdsworth on 26/06/2014.
// Copyright (c) 2014 John Holdsworth.
//
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
//
// This code is in the public domain from:
// https://github.com/johnno1962/SwiftRegex
//
import Foundation
var swiftRegexCache = [String: NSRegularExpression]()
public class SwiftRegex: NSObject, BooleanType {
var target:String
var regex: NSRegularExpression
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
swiftRegexCache[pattern] = regex
self.regex = regex
}
else {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
super.init()
}
class func failure(message: String) {
println("SwiftRegex: "+message)
//assert(false,"SwiftRegex: failed")
}
final var targetRange: NSRange {
return NSRange(location: 0,length: count(target.utf16))
}
final func substring(range: NSRange) -> String? {
if ( range.location != NSNotFound ) {
return (target as NSString).substringWithRange(range)
} else {
return nil
}
}
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
return range(options: options).location != NSNotFound
}
public func range(options: NSMatchingOptions = nil) -> NSRange {
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
}
public func match(options: NSMatchingOptions = nil) -> String? {
return substring(range(options: options))
}
public func groups(options: NSMatchingOptions = nil) -> [String]? {
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
}
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
}
}
return groups
} else {
return nil
}
}
public subscript(groupno: Int) -> String? {
get {
return groups()?[groupno]
}
set(newValue) {
if newValue == nil {
return
}
for match in matchResults()!.reverse() {
let replacement = regex.replacementStringForResult(match,
inString: target as String, offset: 0, template: newValue!)
let mut = NSMutableString(string: target)
mut.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement)
target = mut as String
}
}
}
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
as? [NSTextCheckingResult]
if matches != nil {
return matches!
} else {
return nil
}
}
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
return matchResults(options: options)!.map { $0.range }
}
public func matches(options: NSMatchingOptions = nil) -> [String] {
return matchResults(options: options)!.map( { self.substring($0.range)!})
}
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
return matchResults(options: options)!.map {self.groupsForMatch($0)}
}
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
var out = Dictionary<String,String>()
for match in matchResults(options: options)! {
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
}
return out
}
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
let matchRange = match.range
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
out.appendString( substitution(match, stop) )
pos = matchRange.location + matchRange.length
}
out.appendString(substring(NSRange(location:pos, length:targetRange.length-pos))!)
return out as String
}
public var boolValue: Bool {
return doesMatch()
}
}
extension String {
public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern, options: options)
}
}
extension String {
public subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern)
}
}
public func ~= (left: SwiftRegex, right: String) -> String {
return left.substituteMatches({match, stop in
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: [String]) -> String {
var matchNumber = 0
return left.substituteMatches({match, stop -> String in
if ++matchNumber == right.count {
stop.memory = true
}
return left.regex.replacementStringForResult( match,
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
}, options: nil)
}
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
// return right(left.substring(match.range))
return left.substituteMatches(
{match, stop -> String in
right(left.substring(match.range)!)
}, options: nil)
}
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
return left.substituteMatches({match, stop -> String in
return right(left.groupsForMatch(match))
}, options: nil)
}
@@ -7,7 +7,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
@@ -79,6 +78,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
var buffer: NSMutableData?
}
private var cookies:[NSHTTPCookie]?
public weak var delegate: WebSocketDelegate?
private var url: NSURL
private var inputStream: NSInputStream?
@@ -104,6 +104,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
public init(url: NSURL) {
self.url = url
}
public convenience init(url: NSURL, cookies:[NSHTTPCookie]?) {
self.init(url: url)
self.cookies = cookies
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
@@ -176,6 +181,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
port = 80
}
}
if self.cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
for (key, value) in headers {
self.addHeader(urlRequest, key: key as! String, val: value as! String)
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
@@ -236,8 +249,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
@@ -247,18 +260,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
func stream(aStream: NSStream!, handleEvent eventCode: NSStreamEvent) {
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream!.streamError)
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
@@ -333,7 +346,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
///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("\r"), UInt8("\n"), UInt8("\r"), UInt8("\n")]
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++ {
@@ -369,14 +382,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
///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 {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let acceptKey = headers[headerWSAcceptName] as NSString
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
let headers: NSDictionary = cfHeaders.takeRetainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
@@ -500,7 +513,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = Int(offset+len)
let step = offset + Int(len)
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
@@ -565,7 +578,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
processResponse(response!)
}
let step = Int(offset+len)
let step = offset + Int(len)
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
@@ -597,9 +610,9 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
dispatch_async(queue,{
if let textBlock = self.receivedTextBlock{
textBlock(str!)
textBlock(str! as String)
}
self.delegate?.websocketDidReceiveMessage(self, text: str!)
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
@@ -673,7 +686,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, UInt(sizeof(UInt32)), maskKey)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
@@ -711,4 +724,4 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
}
}
}
-579
View File
@@ -1,579 +0,0 @@
//
// SocketEngine.swift
// Socket.IO-Swift
//
// Created by Erik Little on 3/3/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// 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)
}
}
private typealias PollWaitQueue = [() -> Void]
private enum PacketType: String {
case OPEN = "0"
case CLOSE = "1"
case PING = "2"
case PONG = "3"
case MESSAGE = "4"
case UPGRADE = "5"
case NOOP = "6"
}
class SocketEngine: NSObject, WebSocketDelegate {
unowned let client:SocketIOClient
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create(
"emitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let parseQueue = dispatch_queue_create(
"parseQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create(
"handleQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
private var forcePolling = 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 waitingForPoll = false
private var waitingForPost = false
private var _websocket = false
private var websocketConnected = false
var connected = false
var pingInterval:Int?
var polling:Bool {
return self._polling
}
var sid = ""
var urlPolling:String?
var urlWebSocket:String?
var websocket:Bool {
return self._websocket
}
var ws:WebSocket?
init(client:SocketIOClient, forcePolling:Bool = false) {
self.client = client
self.forcePolling = forcePolling
self.session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: nil, delegateQueue: self.workQueue)
}
func close() {
self.pingTimer?.invalidate()
self.send(PacketType.CLOSE.rawValue)
}
private func createBinaryDataForSend(data:NSData) -> (NSData?, String?) {
if self.websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
var mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return (mutData, nil)
} else {
var str = "b4"
str += data.base64EncodedStringWithOptions(
NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
return (nil, str)
}
}
private func createURLs(params:[String: AnyObject]? = nil) -> (String, String) {
var url = "\(self.client.socketURL)/socket.io/?transport="
var urlPolling:String
var urlWebSocket:String
if self.client.secure {
urlPolling = "https://" + url + "polling"
urlWebSocket = "wss://" + url + "websocket"
} else {
urlPolling = "http://" + url + "polling"
urlWebSocket = "ws://" + url + "websocket"
}
if params != nil {
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(
NSCharacterSet.URLHostAllowedCharacterSet())!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func doPoll() {
if self.urlPolling == nil || self.websocket || self.waitingForPoll || !self.connected {
return
}
let req = NSMutableURLRequest(URL: NSURL(string: self.urlPolling! + "&sid=\(self.sid)")!)
req.timeoutInterval = 0.0
self.waitingForPoll = true
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil {
if self!.polling {
self?.handlePollingFailed(err)
}
return
}
// println(data)
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// println(str)
dispatch_async(self!.parseQueue) {[weak self] in
if self == nil {
return
}
self?.parsePollingMessage(str)
return
}
}
self?.waitingForPoll = false
self?.doPoll()
}.resume()
}
private func flushProbeWait() {
// println("flushing probe wait")
dispatch_async(self.emitQueue) {[weak self] in
if self == nil {
return
}
for waiter in self!.probeWait {
waiter()
}
self?.probeWait.removeAll(keepCapacity: false)
}
}
private func flushWaitingForPost() {
if self.postWait.count == 0 || !self.connected {
return
} else if self.websocket {
self.flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in self.postWait {
let len = countElements(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")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
req.HTTPBody = postData
self.waitingForPost = true
self.session.dataTaskWithRequest(req) {[weak self] data, res, err in
if self == nil {
return
} else if err != nil && self!.polling {
self?.handlePollingFailed(err)
return
}
self?.waitingForPost = false
dispatch_async(self!.emitQueue) {
self?.flushWaitingForPost()
self?.doPoll()
return
}}.resume()
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
for msg in self.postWait {
self.ws?.writeString(msg)
}
self.postWait.removeAll(keepCapacity: true)
}
// A poll failed, tell the client about it
// 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?.disconnect()
self.pingTimer?.invalidate()
self.waitingForPoll = false
self.waitingForPost = false
self.client.pollingDidFail(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.")
}
let (urlPolling, urlWebSocket) = self.createURLs(params: 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 = WebSocket(url: NSURL(string: urlWebSocket + "&sid=\(self!.sid)")!)
self?.ws?.queue = self?.handleQueue
self?.ws?.delegate = self
self?.ws?.connect()
}
} else {
NSLog("Error handshaking")
return
}
if let pingInterval = json["pingInterval"] as? Int {
self?.pingInterval = pingInterval / 1000
}
}
self?.doPoll()
self?.startPingTimer()
}}.resume()
}
// 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)
return
}
msg = String(strArray[i&+1...i&+n])
if let lengthInt = length.toInt() {
if lengthInt != msg.length {
println("parsing error")
return
}
}
if msg.length != 0 {
// Be sure to capture the value of the msg
dispatch_async(self.handleQueue) {[weak self, msg] in
fixSwift = msg
if fixSwift is String {
self?.parseEngineMessage(fixSwift as String)
}
}
}
i += n
length = ""
}
}
}
private func parseEngineData(data:NSData) {
self.client.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
private func parseEngineMessage(var message:String) {
// println(message!)
var strMessage = RegexMutable(message)
// We should upgrade
if strMessage == "3probe" {
self.upgradeTransport()
return
}
let type = strMessage["^(\\d)"].groups()?[1]
if type != PacketType.MESSAGE.rawValue {
// TODO Handle other packets
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
// println("sending \(data)")
self.client.parseBinaryData(data)
}
return
} else if type == PacketType.NOOP.rawValue {
self.doPoll()
return
}
if message == PacketType.CLOSE.rawValue {
// do nothing
return
}
// println("Got something idk what to do with")
// println(messageString)
}
// Remove message type
message.removeAtIndex(message.startIndex)
// println("sending \(messageString)")
self.client.parseSocketMessage(message)
}
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)()
}
}
}
func sendPing() {
if self.websocket {
self.sendWebSocketMessage("", withType: PacketType.PING)
} else {
self.sendPollMessage("", withType: PacketType.PING)
}
}
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?.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,
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()
}
}
func websocketDidConnect(socket:WebSocket) {
self.websocketConnected = true
self.probing = true
self.probeWebSocket()
}
func websocketDidDisconnect(socket:WebSocket, error:NSError?) {
self.websocketConnected = false
self.probing = false
if self.websocket {
self.pingTimer?.invalidate()
self.connected = false
self._websocket = false
self._polling = true
self.client.webSocketDidCloseWithCode(1, reason: "Socket Disconnect", wasClean: true)
} else {
self.flushProbeWait()
}
}
func websocketDidReceiveMessage(socket:WebSocket, text:String) {
self.parseEngineMessage(text)
}
func websocketDidReceiveData(socket:WebSocket, data:NSData) {
self.parseEngineData(data)
}
}
-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
}
}
-845
View File
@@ -1,845 +0,0 @@
//
// SocketIOClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 11/23/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public class SocketIOClient: NSObject {
let socketURL:NSMutableString!
let ackQueue = dispatch_queue_create("ackQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let handleQueue = dispatch_queue_create("handleQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let emitQueue = dispatch_queue_create("emitQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let reconnectAttempts:Int!
private lazy var params = [String: AnyObject]()
private var ackHandlers = [SocketAckHandler]()
private var anyHandler:((AnyHandler) -> Void)?
private var currentAck = -1
private var currentReconnectAttempt = 0
private var forcePolling = false
private var handlers = [SocketEventHandler]()
private var waitingData = [SocketEvent]()
private var paramConnect = false
private var _secure = false
private var reconnectTimer:NSTimer?
var closed = false
var connected = false
var connecting = false
var engine:SocketEngine?
var nsp:String?
var reconnects = true
var reconnecting = false
var reconnectWait = 10
var secure:Bool {
return self._secure
}
var sid:String?
public init(socketURL:String, opts:[String: AnyObject]? = nil) {
var mutURL = RegexMutable(socketURL)
if mutURL["https://"].matches().count != 0 {
self._secure = true
}
mutURL = mutURL["http://"] ~= ""
mutURL = mutURL["https://"] ~= ""
self.socketURL = mutURL
// Set options
if opts != nil {
if let reconnects = opts!["reconnects"] as? Bool {
self.reconnects = reconnects
}
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts!["reconnectWait"] as? Int {
self.reconnectWait = abs(reconnectWait)
}
if let nsp = opts!["nsp"] as? String {
self.nsp = nsp
}
if let polling = opts!["forcePolling"] as? Bool {
self.forcePolling = polling
}
} else {
self.reconnectAttempts = -1
}
super.init()
self.engine = SocketEngine(client: self, forcePolling: self.forcePolling)
}
// Closes the socket
public func close() {
self.closed = true
self.connecting = false
self.connected = false
self.reconnecting = false
self.engine?.close()
}
// Connects to the server
public func connect() {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self.closed = false
}
self.engine?.open()
}
// Connect to the server using params
public func connectWithParams(params:[String: AnyObject]) {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self.closed = false
}
self.params = params
self.paramConnect = true
self.engine?.open(opts: params)
}
func didConnect() {
self.closed = false
self.connected = true
self.connecting = false
self.reconnecting = false
self.currentReconnectAttempt = 0
self.reconnectTimer?.invalidate()
self.reconnectTimer = nil
self.handleEvent("connect", data: nil, isInternalMessage: false)
}
// Server wants us to die
func didForceClose() {
self.closed = true
self.connected = false
self.reconnects = false
self.connecting = false
self.reconnecting = false
self.handleEvent("disconnect", data: "closed", isInternalMessage: true)
}
// Sends a message with multiple args
// If a message contains binary we have to send those
// seperately.
public func emit(event:String, _ args:AnyObject...) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, args)
return
}
}
// Objc doesn't have variadics
public func emitObjc(event:String, _ args:[AnyObject]) {
self.emit(event, args)
}
public func emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler {
if !self.connected {
return SocketAckHandler(event: "fail")
}
self.currentAck++
let ackHandler = SocketAckHandler(event: event, ackNum: self.currentAck)
self.ackHandlers.append(ackHandler)
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, args, ack: true)
return
}
return ackHandler
}
public func emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler {
return self.emitWithAck(event, args)
}
private func _emit(event:String, _ args:[AnyObject], ack:Bool = false) {
var frame:SocketEvent
var str:String
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(args)
if !self.connected {
return
}
if hasBinary {
if !ack {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp, wantsAck: self.currentAck)
}
self.engine?.send(str, datas: emitDatas)
} else {
if !ack {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp, wantsAck: self.currentAck)
}
self.engine?.send(str)
}
}
// If the server wants to know that the client received data
internal func emitAck(ack:Int, withData data:[AnyObject]?, withAckType ackType:Int) {
dispatch_async(self.ackQueue) {[weak self] in
if self == nil || !self!.connected || data == nil {
return
}
let (items, hasBinary, emitDatas) = SocketIOClient.parseEmitArgs(data!)
var str:String
if !hasBinary {
if self?.nsp == nil {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 3, withNsp: "/")
} else {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 3, withNsp: self!.nsp!)
}
self?.engine?.send(str)
} else {
if self?.nsp == nil {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 6, withNsp: "/", withBinary: emitDatas.count)
} else {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 6, withNsp: self!.nsp!, withBinary: emitDatas.count)
}
self?.engine?.send(str, datas: emitDatas)
}
}
}
// Called when the socket gets an ack for something it sent
private func handleAck(ack:Int, data:AnyObject?) {
self.ackHandlers = self.ackHandlers.filter {handler in
if handler.ackNum != ack {
return true
} else {
if data is NSArray {
handler.executeAck(data as? NSArray)
} else if data != nil {
handler.executeAck([data!])
} else {
handler.executeAck(nil)
}
return false
}
}
}
// Handles events
public func handleEvent(event:String, data:AnyObject?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil, withAckType ackType:Int = 3) {
// println("Should do event: \(event) with data: \(data)")
if !self.connected && !isInternalMessage {
return
}
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.anyHandler?((event, data))
return
}
for handler in self.handlers {
if handler.event == event {
if data is NSArray {
if ack != nil {
handler.executeCallback(data as? NSArray, withAck: ack!,
withAckType: ackType, withSocket: self)
} else {
handler.executeCallback(data as? NSArray)
}
} else {
// Trying to do a ternary expression in the executeCallback method
// seemed to crash Swift
var dataArr:NSArray? = nil
if let data:AnyObject = data {
dataArr = [data]
}
if ack != nil {
handler.executeCallback(dataArr, withAck: ack!,
withAckType: ackType, withSocket: self)
} else {
handler.executeCallback(dataArr)
}
}
}
}
}
// Should be removed and moved to SocketEngine
func joinNamespace() {
if self.nsp != nil {
self.engine?.send("0/\(self.nsp!)")
}
}
// Adds handler for an event
public func on(name:String, callback:NormalCallback) {
let handler = SocketEventHandler(event: name, callback: callback)
self.handlers.append(handler)
}
// Adds a handler for any event
public func onAny(handler:(AnyHandler) -> Void) {
self.anyHandler = handler
}
// Opens the connection to the socket
public func open() {
self.connect()
}
// Parse an NSArray looking for binary data
private class func parseArray(arr:NSArray, var currentPlaceholder:Int) -> (NSArray, Bool, [NSData]) {
var replacementArr = [AnyObject](count: arr.count, repeatedValue: 1)
var hasBinary = false
var arrayDatas = [NSData]()
for g in 0..<arr.count {
if arr[g] is NSData {
hasBinary = true
currentPlaceholder++
let sendData = arr[g] as NSData
arrayDatas.append(sendData)
replacementArr[g] = ["_placeholder": true,
"num": currentPlaceholder]
} else if let dict = arr[g] as? NSDictionary {
let (nestDict, hadBinary, dictArrs) = self.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += dictArrs.count
replacementArr[g] = nestDict
arrayDatas.extend(dictArrs)
} else {
replacementArr[g] = dict
}
} else if let nestArr = arr[g] as? NSArray {
// Recursive
let (nested, hadBinary, nestDatas) = self.parseArray(nestArr,
currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
currentPlaceholder += nestDatas.count
replacementArr[g] = nested
arrayDatas.extend(nestDatas)
} else {
replacementArr[g] = arr[g]
}
} else {
replacementArr[g] = arr[g]
}
}
return (replacementArr, hasBinary, arrayDatas)
}
// Parses data for events
class func parseData(data:String?) -> AnyObject? {
if data == nil {
return nil
}
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
}
private class func parseEmitArgs(args:[AnyObject]) -> ([AnyObject], Bool, [NSData]) {
var items = [AnyObject](count: args.count, repeatedValue: 1)
var currentPlaceholder = -1
var hasBinary = false
var emitDatas = [NSData]()
for i in 0..<args.count {
if let dict = args[i] as? NSDictionary {
// Check for binary data
let (newDict, hadBinary, binaryDatas) = SocketIOClient.parseNSDictionary(dict,
currentPlaceholder: currentPlaceholder)
if hadBinary {
currentPlaceholder += binaryDatas.count
emitDatas.extend(binaryDatas)
hasBinary = true
items[i] = newDict
} else {
items[i] = dict
}
} else if let arr = args[i] as? NSArray {
// arg is array, check for binary
let (replace, hadData, newDatas) = SocketIOClient.parseArray(arr,
currentPlaceholder: currentPlaceholder)
if hadData {
hasBinary = true
currentPlaceholder += newDatas.count
for data in newDatas {
emitDatas.append(data)
}
items[i] = replace
} else {
items[i] = arr
}
} else if let binaryData = args[i] as? NSData {
// args is just binary
hasBinary = true
currentPlaceholder++
items[i] = ["_placeholder": true, "num": currentPlaceholder]
emitDatas.append(binaryData)
} else {
items[i] = args[i]
}
}
return (items, hasBinary, emitDatas)
}
// Parses a NSDictionary, looking for NSData objects
private class func parseNSDictionary(dict:NSDictionary, var currentPlaceholder:Int) -> (NSDictionary, Bool, [NSData]) {
var returnDict = NSMutableDictionary()
var hasBinary = false
var returnDatas = [NSData]()
for (key, value) in dict {
if let binaryData = value as? NSData {
currentPlaceholder++
hasBinary = true
returnDatas.append(binaryData)
returnDict[key as String] = ["_placeholder": true, "num": currentPlaceholder++]
} else if let arr = value as? NSArray {
let (replace, hadBinary, arrDatas) = self.parseArray(arr, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = replace
currentPlaceholder += arrDatas.count
returnDatas.extend(arrDatas)
} else {
returnDict[key as String] = arr
}
} else if let dict = value as? NSDictionary {
// Recursive
let (nestDict, hadBinary, nestDatas) = self.parseNSDictionary(dict, currentPlaceholder: currentPlaceholder)
if hadBinary {
hasBinary = true
returnDict[key as String] = nestDict
currentPlaceholder += nestDatas.count
returnDatas.extend(nestDatas)
} else {
returnDict[key as String] = dict
}
} else {
returnDict[key as String] = value
}
}
return (returnDict, hasBinary, returnDatas)
}
// Parses messages recieved
internal func parseSocketMessage(stringMessage:String) {
// println(message!)
// Check for successful namepsace connect
if self.nsp != nil {
if stringMessage == "0/\(self.nsp!)" {
self.didConnect()
return
}
}
if stringMessage == "0" {
if self.nsp != nil {
// Join namespace
self.joinNamespace()
return
} else {
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.didConnect()
return
}
}
var mutMessage = RegexMutable(stringMessage)
/**
Begin check for message
**/
let messageGroups = mutMessage["(\\d*)\\/?(\\w*)?,?(\\d*)?(\\[.*\\])?"].groups()
if messageGroups[1].hasPrefix("2") {
var mesNum = messageGroups[1]
var ackNum:String
var namespace:String?
var messagePart:String!
if messageGroups[3] != "" {
ackNum = messageGroups[3]
} else {
let range = Range<String.Index>(start: mesNum.startIndex, end: advance(mesNum.startIndex, 1))
mesNum.replaceRange(range, with: "")
ackNum = mesNum
}
namespace = messageGroups[2]
messagePart = messageGroups[4]
if namespace == "" && self.nsp != nil {
return
}
let messageInternals = RegexMutable(messagePart)["\\[\"(.*?)\",(.*?)?\\]$"].groups()
if messageInternals != nil && messageInternals.count > 2 {
let event = messageInternals[1]
var data:String?
if messageInternals[2] == "" {
data = nil
} else {
data = messageInternals[2]
}
// It would be nice if socket.io only allowed one thing
// per message, but alas, it doesn't.
if let parsed:AnyObject = SocketIOClient.parseData(data) {
if ackNum == "" {
self.handleEvent(event, data: parsed)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: parsed, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
} else if let strData = data {
// There are multiple items in the message
// Turn it into a String and run it through
// parseData to try and get an array.
let asArray = "[\(strData)]"
if let parsed:AnyObject = SocketIOClient.parseData(asArray) {
if ackNum == "" {
self.handleEvent(event, data: parsed)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: parsed, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
}
}
}
// Check for no item event
let noItemMessage = RegexMutable(messagePart)["\\[\"(.*?)\"]$"].groups()
if noItemMessage != nil && noItemMessage.count == 2 {
let event = noItemMessage[1]
if ackNum == "" {
self.handleEvent(event, data: nil)
} else {
self.currentAck = ackNum.toInt()!
self.handleEvent(event, data: nil, isInternalMessage: false,
wantsAck: ackNum.toInt(), withAckType: 3)
}
return
}
} else if messageGroups[1].hasPrefix("3") {
let arr = Array(messageGroups[1])
var ackNum:String
let nsp = messageGroups[2]
if nsp == "" && self.nsp != nil {
return
}
if nsp == "" {
ackNum = String(arr[1...arr.count-1])
} else {
ackNum = messageGroups[3]
}
let ackData:AnyObject? = SocketIOClient.parseData(messageGroups[4])
self.handleAck(ackNum.toInt()!, data: ackData)
return
}
/**
End Check for message
**/
// Check for message with binary placeholders
self.parseBinaryMessage(message: stringMessage)
}
// Tries to parse a message that contains binary
private func parseBinaryMessage(#message:AnyObject) {
// println(message)
if let stringMessage = message as? String {
var mutMessage = RegexMutable(stringMessage)
/**
Begin check for binary placeholders
**/
let binaryGroup = mutMessage["^(\\d*)-\\/?(\\w*)?,?(\\d*)?\\[(\".*?\")?,?(.*)?\\]$"].groups()
if binaryGroup == nil {
return
}
if binaryGroup[1].hasPrefix("5") {
// println(binaryGroup)
var ackNum:String
var event:String
var mutMessageObject:NSMutableString
var namespace:String?
var numberOfPlaceholders:String
let messageType = RegexMutable(binaryGroup[1])
namespace = binaryGroup[2]
if binaryGroup[3] != "" {
ackNum = binaryGroup[3] as String
} else if self.nsp == nil && binaryGroup[2] != "" {
ackNum = binaryGroup[2]
} else {
ackNum = ""
}
numberOfPlaceholders = (messageType["5"] ~= "") as String
event = (RegexMutable(binaryGroup[4])["\""] ~= "") as String
mutMessageObject = RegexMutable(binaryGroup[5])
if namespace == "" && self.nsp != nil {
return
}
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
var mes:SocketEvent
if ackNum == "" {
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!)
} else {
self.currentAck = ackNum.toInt()!
mes = SocketEvent(event: event, args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt())
}
self.waitingData.append(mes)
} else if binaryGroup[1].hasPrefix("6") {
let messageType = RegexMutable(binaryGroup[1])
let numberOfPlaceholders = (messageType["6"] ~= "") as String
var ackNum:String
var nsp:String
if binaryGroup[3] == "" {
ackNum = binaryGroup[2]
nsp = ""
} else {
ackNum = binaryGroup[3]
nsp = binaryGroup[2]
}
if nsp == "" && self.nsp != nil {
return
}
var mutMessageObject = RegexMutable(binaryGroup[5])
let placeholdersRemoved = mutMessageObject["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"]
~= "\"~~$2\""
let event = SocketEvent(event: "", args: placeholdersRemoved,
placeholders: numberOfPlaceholders.toInt()!, ackNum: ackNum.toInt(), justAck: true)
self.waitingData.append(event)
}
/**
End check for binary placeholders
**/
}
}
// Handles binary data
internal func parseBinaryData(data:NSData) {
let shouldExecute = self.waitingData[0].addData(data)
if shouldExecute {
let socketEvent = self.waitingData.removeAtIndex(0)
var event = socketEvent.event
var parsedArgs:AnyObject? = SocketIOClient.parseData(socketEvent.args as? String)
if let args:AnyObject = parsedArgs {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders(args)
if socketEvent.justAck! {
// Should handle ack
self.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should do event
if socketEvent.ack != nil {
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
self.handleEvent(event, data: filledInArgs)
}
} else {
let filledInArgs:AnyObject = socketEvent.fillInPlaceholders()
// Should handle ack
if socketEvent.justAck! {
self.handleAck(socketEvent.ack!, data: filledInArgs)
return
}
// Should handle ack
if socketEvent.ack != nil {
self.handleEvent(event, data: filledInArgs, isInternalMessage: false,
wantsAck: socketEvent.ack!, withAckType: 6)
} else {
self.handleEvent(event, data: filledInArgs)
}
}
}
}
// Something happened while polling
internal func pollingDidFail(err:NSError?) {
if !self.reconnecting {
self.connected = false
self.handleEvent("reconnect", data: err?.localizedDescription, isInternalMessage: true)
self.tryReconnect()
}
}
// We lost connection and should attempt to reestablish
internal func tryReconnect() {
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
self.didForceClose()
return
} else if self.connected {
self.connecting = false
self.reconnecting = false
return
}
if self.reconnectTimer == nil {
self.reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
return
}
}
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
isInternalMessage: true)
self.currentReconnectAttempt++
if self.paramConnect {
self.connectWithParams(self.params)
} else {
self.connect()
}
}
// Called when the socket is closed
func webSocketDidCloseWithCode(code:Int, reason:String!, wasClean:Bool) {
self.connected = false
self.connecting = false
if self.closed || !self.reconnects {
self.didForceClose()
} else {
self.handleEvent("reconnect", data: reason, isInternalMessage: true)
self.tryReconnect()
}
}
// Called when an error occurs.
func webSocketDidFailWithError(error:NSError!) {
self.connected = false
self.connecting = false
self.handleEvent("error", data: error.localizedDescription, isInternalMessage: true)
if self.closed || !self.reconnects {
self.didForceClose()
} else if !self.reconnecting {
self.handleEvent("reconnect", data: error.localizedDescription, isInternalMessage: true)
self.tryReconnect()
}
}
}
-329
View File
@@ -1,329 +0,0 @@
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by John Holdsworth on 26/06/2014.
// Copyright (c) 2014 John Holdsworth.
//
// $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $
//
// This code is in the public domain from:
// https://github.com/johnno1962/SwiftRegex
//
import Foundation
var swiftRegexCache = [String: NSRegularExpression]()
public class SwiftRegex: NSObject, BooleanType {
var target: NSString
var regex: NSRegularExpression
init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) {
self.target = target
if let regex = swiftRegexCache[pattern] {
self.regex = regex
} else {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
swiftRegexCache[pattern] = regex
self.regex = regex
}
else {
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
self.regex = NSRegularExpression()
}
}
super.init()
}
class func failure(message: String) {
println("SwiftRegex: "+message)
//assert(false,"SwiftRegex: failed")
}
final var targetRange: NSRange {
return NSRange(location: 0,length: target.length)
}
final func substring(range: NSRange) -> NSString! {
if ( range.location != NSNotFound ) {
return target.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 groups(options: NSMatchingOptions = nil) -> [String]! {
return groupsForMatch( regex.firstMatchInString(target as String, options: options, range: targetRange) )
}
func groupsForMatch(match: NSTextCheckingResult!) -> [String]! {
if match != nil {
var groups = [String]()
for groupno in 0...regex.numberOfCaptureGroups {
if let group = substring(match.rangeAtIndex(groupno)) as String! {
groups += [group]
} else {
groups += ["_"] // avoids bridging problems
}
}
return groups
} else {
return nil
}
}
public subscript(groupno: Int) -> String! {
get {
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")
}
}
}
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 } )
}
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))
}
return out
}
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
options:NSMatchingOptions = nil) -> NSMutableString {
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( 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
}
}
/* 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)
}
}
extension String {
public subscript(pattern: String) -> SwiftRegex {
return SwiftRegex(target: self, pattern: pattern)
}
}
public func RegexMutable(string: NSString) -> NSMutableString {
return NSMutableString(string:string as String)
}
public func ~= (left: SwiftRegex, right: String) -> NSMutableString {
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 {
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)
})
}