forked from pkyeck/socket.IO-objc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketIO.m
executable file
·887 lines (734 loc) · 26.7 KB
/
SocketIO.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//
// SocketIO.m
// v0.2.5 ARC
//
// based on
// socketio-cocoa https://github.com/fpotter/socketio-cocoa
// by Fred Potter <[email protected]>
//
// using
// https://github.com/square/SocketRocket
// https://github.com/stig/json-framework/
//
// reusing some parts of
// /socket.io/socket.io.js
//
// Created by Philipp Kyeck http://beta-interactive.de
//
// Updated by
// samlown https://github.com/samlown
// kayleg https://github.com/kayleg
// taiyangc https://github.com/taiyangc
//
#import "SocketIO.h"
#import "SocketIOJSONSerialization.h"
#import "SRWebSocket.h"
#define DEBUG_LOGS 0
#define DEBUG_CERTIFICATE 1
#if DEBUG_LOGS
#define DEBUGLOG(...) NSLog(__VA_ARGS__)
#else
#define DEBUGLOG(...)
#endif
static NSString* kInsecureHandshakeURL = @"http://%@/socket.io/1/?t=%d%@";
static NSString* kInsecureHandshakePortURL = @"http://%@:%d/socket.io/1/?t=%d%@";
static NSString* kSecureHandshakePortURL = @"https://%@:%d/socket.io/1/?t=%d%@";
static NSString* kSecureHandshakeURL = @"https://%@/socket.io/1/?t=%d%@";
static NSString* kInsecureSocketURL = @"ws://%@/socket.io/1/websocket/%@";
static NSString* kSecureSocketURL = @"wss://%@/socket.io/1/websocket/%@";
static NSString* kInsecureXHRURL = @"http://%@/socket.io/1/xhr-polling/%@";
static NSString* kSecureXHRURL = @"https://%@/socket.io/1/xhr-polling/%@";
static NSString* kInsecureSocketPortURL = @"ws://%@:%d/socket.io/1/websocket/%@";
static NSString* kSecureSocketPortURL = @"wss://%@:%d/socket.io/1/websocket/%@";
static NSString* kInsecureXHRPortURL = @"http://%@:%d/socket.io/1/xhr-polling/%@";
static NSString* kSecureXHRPortURL = @"https://%@:%d/socket.io/1/xhr-polling/%@";
NSString* const SocketIOError = @"SocketIOError";
NSString* const SocketIOException = @"SocketIOException";
# pragma mark -
# pragma mark SocketIO's private interface
@interface SocketIO (Private) <SRWebSocketDelegate>
- (NSArray*) arrayOfCaptureComponentsMatchedByRegex:(NSString*)regex;
- (void) setTimeout;
- (void) onTimeout;
- (void) onConnect:(SocketIOPacket *)packet;
- (void) onDisconnect:(NSError *)error;
- (void) sendDisconnect;
- (void) sendHearbeat;
- (void) send:(SocketIOPacket *)packet;
- (NSString *) addAcknowledge:(SocketIOCallback)function;
- (void) removeAcknowledgeForKey:(NSString *)key;
- (NSMutableArray*) getMatchesFrom:(NSString*)data with:(NSString*)regex;
@end
# pragma mark -
# pragma mark SocketIO implementation
@implementation SocketIO
@synthesize isConnected = _isConnected,
isConnecting = _isConnecting,
useSecure = _useSecure,
delegate = _delegate;
- (id) initWithDelegate:(id<SocketIODelegate>)delegate
{
self = [super init];
if (self) {
_delegate = delegate;
_queue = [[NSMutableArray alloc] init];
_ackCount = 0;
_acks = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) connectToHost:(NSString *)host onPort:(NSInteger)port
{
[self connectToHost:host onPort:port withParams:nil withNamespace:@""];
}
- (void) connectToHost:(NSString *)host onPort:(NSInteger)port withParams:(NSDictionary *)params
{
[self connectToHost:host onPort:port withParams:params withNamespace:@""];
}
- (void) connectToHost:(NSString *)host onPort:(NSInteger)port withParams:(NSDictionary *)params withNamespace:(NSString *)endpoint
{
if (!_isConnected && !_isConnecting) {
_isConnecting = YES;
_host = host;
_port = port;
_params = params;
_endpoint = [endpoint copy];
// create a query parameters string
NSMutableString *query = [[NSMutableString alloc] initWithString:@""];
[params enumerateKeysAndObjectsUsingBlock: ^(id key, id value, BOOL *stop) {
[query appendFormat:@"&%@=%@", key, value];
}];
// do handshake via HTTP request
NSString *s;
NSString *format;
if (_port) {
format = _useSecure ? kSecureHandshakePortURL : kInsecureHandshakePortURL;
s = [NSString stringWithFormat:format, _host, _port, rand(), query];
}
else {
format = _useSecure ? kSecureHandshakeURL : kInsecureHandshakeURL;
s = [NSString stringWithFormat:format, _host, rand(), query];
}
DEBUGLOG(@"Connecting to socket with URL: %@", s);
NSURL *url = [NSURL URLWithString:s];
query = nil;
// make a request
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10.0];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
delegate:self];
if (connection) {
_httpRequestData = [NSMutableData data];
}
else {
// connection failed
[self connection:connection didFailWithError:nil];
}
}
}
- (void) disconnect
{
[self sendDisconnect];
}
- (void) sendMessage:(NSString *)data
{
[self sendMessage:data withAcknowledge:nil];
}
- (void) sendMessage:(NSString *)data withAcknowledge:(SocketIOCallback)function
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"message"];
packet.data = data;
packet.pId = [self addAcknowledge:function];
[self send:packet];
}
- (void) sendJSON:(NSDictionary *)data
{
[self sendJSON:data withAcknowledge:nil];
}
- (void) sendJSON:(NSDictionary *)data withAcknowledge:(SocketIOCallback)function
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"json"];
packet.data = [SocketIOJSONSerialization JSONStringFromObject:data error:nil];
packet.pId = [self addAcknowledge:function];
[self send:packet];
}
- (void) sendEvent:(NSString *)eventName withData:(id)data
{
[self sendEvent:eventName withData:data andAcknowledge:nil];
}
- (void) sendEvent:(NSString *)eventName withData:(id)data andAcknowledge:(SocketIOCallback)function
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:eventName forKey:@"name"];
// do not require arguments
if (data != nil) {
[dict setObject:[NSArray arrayWithObject:data] forKey:@"args"];
}
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"event"];
packet.data = [SocketIOJSONSerialization JSONStringFromObject:dict error:nil];
packet.pId = [self addAcknowledge:function];
if (function) {
packet.ack = @"data";
}
[self send:packet];
}
- (void) sendAcknowledgement:(NSString *)pId withArgs:(NSArray *)data
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"ack"];
packet.data = [SocketIOJSONSerialization JSONStringFromObject:data error:nil];
packet.pId = pId;
packet.ack = @"data";
[self send:packet];
}
# pragma mark -
# pragma mark private methods
- (void) openSocket
{
NSString *urlStr;
NSString *format;
if(_port) {
format = _useSecure ? kSecureSocketPortURL : kInsecureSocketPortURL;
urlStr = [NSString stringWithFormat:format, _host, _port, _sid];
}
else {
format = _useSecure ? kSecureSocketURL : kInsecureSocketURL;
urlStr = [NSString stringWithFormat:format, _host, _sid];
}
NSURL *url = [NSURL URLWithString:urlStr];
_webSocket = nil;
_webSocket = [[SRWebSocket alloc] initWithURL:url];
_webSocket.delegate = self;
DEBUGLOG(@"Opening %@", url);
[_webSocket open];
}
- (void) openXHRPolling
{
NSString *url;
NSString *format;
if (_port) {
format = _useSecure ? kSecureXHRPortURL : kInsecureXHRPortURL;
url = [NSString stringWithFormat:format, _host, _port, _sid];
}
else {
format = _useSecure ? kSecureXHRURL : kInsecureXHRURL;
url = [NSString stringWithFormat:format, _host, _sid];
}
DEBUGLOG(@"Opening XHR @ %@", url);
// TODO: implement
}
- (void) sendDisconnect
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"disconnect"];
[self send:packet];
}
- (void) sendConnect
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"connect"];
[self send:packet];
}
- (void) sendHeartbeat
{
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"heartbeat"];
[self send:packet];
}
- (void) send:(SocketIOPacket *)packet
{
DEBUGLOG(@"send()");
NSNumber *type = [packet typeAsNumber];
NSMutableArray *encoded = [NSMutableArray arrayWithObject:type];
NSString *pId = packet.pId != nil ? packet.pId : @"";
if ([packet.ack isEqualToString:@"data"]) {
pId = [pId stringByAppendingString:@"+"];
}
// Do not write pid for acknowledgements
if ([type intValue] != 6) {
[encoded addObject:pId];
}
// Add the end point for the namespace to be used, as long as it is not
// an ACK, heartbeat, or disconnect packet
if ([type intValue] != 6 && [type intValue] != 2 && [type intValue] != 0) {
[encoded addObject:_endpoint];
}
else {
[encoded addObject:@""];
}
if (packet.data != nil) {
NSString *ackpId = @"";
// This is an acknowledgement packet, so, prepend the ack pid to the data
if ([type intValue] == 6) {
ackpId = [NSString stringWithFormat:@":%@%@", packet.pId, @"+"];
}
[encoded addObject:[NSString stringWithFormat:@"%@%@", ackpId, packet.data]];
}
NSString *req = [encoded componentsJoinedByString:@":"];
if (_webSocket.readyState != SR_OPEN) {
DEBUGLOG(@"queue >>> %@", req);
[_queue addObject:packet];
}
else {
DEBUGLOG(@"send() >>> %@", req);
[_webSocket send:req];
if ([_delegate respondsToSelector:@selector(socketIO:didSendMessage:)]) {
[_delegate socketIO:self didSendMessage:packet];
}
}
}
- (void) onData:(NSString *)data
{
DEBUGLOG(@"onData %@", data);
// data arrived -> reset timeout
[self setTimeout];
// check if data is valid (from socket.io.js)
NSString *regex = @"^([^:]+):([0-9]+)?(\\+)?:([^:]+)?:?(.*)?$";
NSString *regexPieces = @"^([0-9]+)(\\+)?(.*)";
// create regex result
NSMutableArray *test = [self getMatchesFrom:data with:regex];
// valid data-string arrived
if ([test count] > 0) {
NSArray *result = [test objectAtIndex:0];
int idx = [[result objectAtIndex:1] intValue];
SocketIOPacket *packet = [[SocketIOPacket alloc] initWithTypeIndex:idx];
packet.pId = [result objectAtIndex:2];
packet.ack = [result objectAtIndex:3];
packet.endpoint = [result objectAtIndex:4];
packet.data = [result objectAtIndex:5];
//
switch (idx) {
case 0: {
DEBUGLOG(@"disconnect");
[self onDisconnect:[NSError errorWithDomain:SocketIOError
code:SocketIOServerRespondedWithDisconnect
userInfo:nil]];
break;
}
case 1: {
DEBUGLOG(@"connect");
// from socket.io.js ... not sure when data will contain sth?!
// packet.qs = data || '';
[self onConnect:packet];
break;
}
case 2: {
DEBUGLOG(@"heartbeat");
[self sendHeartbeat];
break;
}
case 3: {
DEBUGLOG(@"message");
if (packet.data && ![packet.data isEqualToString:@""]) {
if ([_delegate respondsToSelector:@selector(socketIO:didReceiveMessage:)]) {
[_delegate socketIO:self didReceiveMessage:packet];
}
}
break;
}
case 4: {
DEBUGLOG(@"json");
if (packet.data && ![packet.data isEqualToString:@""]) {
if ([_delegate respondsToSelector:@selector(socketIO:didReceiveJSON:)]) {
[_delegate socketIO:self didReceiveJSON:packet];
}
}
break;
}
case 5: {
DEBUGLOG(@"event");
if (packet.data && ![packet.data isEqualToString:@""]) {
NSDictionary *json = [packet dataAsJSON];
packet.name = [json objectForKey:@"name"];
packet.args = [json objectForKey:@"args"];
if ([_delegate respondsToSelector:@selector(socketIO:didReceiveEvent:)]) {
[_delegate socketIO:self didReceiveEvent:packet];
}
}
break;
}
case 6: {
DEBUGLOG(@"ack");
// create regex result
NSMutableArray *pieces = [self getMatchesFrom:packet.data with:regexPieces];
if ([pieces count] > 0) {
NSArray *piece = [pieces objectAtIndex:0];
int ackId = [[piece objectAtIndex:1] intValue];
DEBUGLOG(@"ack id found: %d", ackId);
NSString *argsStr = [piece objectAtIndex:3];
id argsData = nil;
if (argsStr && ![argsStr isEqualToString:@""]) {
argsData = [SocketIOJSONSerialization objectFromJSONData:[argsStr dataUsingEncoding:NSUTF8StringEncoding] error:nil];
if ([argsData count] > 0) {
argsData = [argsData objectAtIndex:0];
}
}
// get selector for ackId
NSString *key = [NSString stringWithFormat:@"%d", ackId];
SocketIOCallback callbackFunction = [_acks objectForKey:key];
if (callbackFunction != nil) {
callbackFunction(argsData);
[self removeAcknowledgeForKey:key];
}
}
break;
}
case 7: {
DEBUGLOG(@"error");
break;
}
case 8: {
DEBUGLOG(@"noop");
break;
}
default: {
DEBUGLOG(@"command not found or not yet supported");
break;
}
}
packet = nil;
}
else {
DEBUGLOG(@"ERROR: data that has arrived wasn't valid");
}
}
- (void) doQueue
{
DEBUGLOG(@"doQueue() >> %lu", (unsigned long)[_queue count]);
// TODO send all packets at once ... not as seperate packets
while ([_queue count] > 0) {
SocketIOPacket *packet = [_queue objectAtIndex:0];
[self send:packet];
[_queue removeObject:packet];
}
}
- (void) onConnect:(SocketIOPacket *)packet
{
DEBUGLOG(@"onConnect()");
_isConnected = YES;
// Send the connected packet so the server knows what it's dealing with.
// Only required when endpoint/namespace is present
if ([_endpoint length] > 0) {
// Make sure the packet we received has an endpoint, otherwise send it again
if (![packet.endpoint isEqualToString:_endpoint]) {
DEBUGLOG(@"onConnect() >> End points do not match, resending connect packet");
[self sendConnect];
return;
}
}
_isConnecting = NO;
if ([_delegate respondsToSelector:@selector(socketIODidConnect:)]) {
[_delegate socketIODidConnect:self];
}
// send any queued packets
[self doQueue];
[self setTimeout];
}
- (void) onDisconnect:(NSError *)error
{
DEBUGLOG(@"onDisconnect()");
BOOL wasConnected = _isConnected;
BOOL wasConnecting = _isConnecting;
_isConnected = NO;
_isConnecting = NO;
_sid = nil;
[_queue removeAllObjects];
// Kill the heartbeat timer
if (_timeout != nil) {
[_timeout invalidate];
_timeout = nil;
}
// Disconnect the websocket, just in case
if (_webSocket != nil) {
// clear websocket's delegate - otherwise crashes
_webSocket.delegate = nil;
[_webSocket close];
}
if ((wasConnected || wasConnecting)) {
// first look for the new disconnectedWithError then the old one (backwards compatibility)
if ([_delegate respondsToSelector:@selector(socketIODidDisconnect:disconnectedWithError:)]) {
[_delegate socketIODidDisconnect:self disconnectedWithError:error];
}
else if ([_delegate respondsToSelector:@selector(socketIODidDisconnect:)]) {
[_delegate socketIODidDisconnect:self];
}
}
}
# pragma mark -
# pragma mark Acknowledge methods
- (NSString *) addAcknowledge:(SocketIOCallback)function
{
if (function) {
++_ackCount;
NSString *ac = [NSString stringWithFormat:@"%ld", (long)_ackCount];
[_acks setObject:[function copy] forKey:ac];
return ac;
}
return nil;
}
- (void) removeAcknowledgeForKey:(NSString *)key
{
[_acks removeObjectForKey:key];
}
# pragma mark -
# pragma mark Heartbeat methods
- (void) onTimeout
{
DEBUGLOG(@"Timed out waiting for heartbeat.");
[self onDisconnect:[NSError errorWithDomain:SocketIOError
code:SocketIOHeartbeatTimeout
userInfo:nil]];
}
- (void) setTimeout
{
DEBUGLOG(@"setTimeout()");
if (_timeout != nil) {
[_timeout invalidate];
_timeout = nil;
}
_timeout = [NSTimer scheduledTimerWithTimeInterval:_heartbeatTimeout
target:self
selector:@selector(onTimeout)
userInfo:nil
repeats:NO];
}
# pragma mark -
# pragma mark Regex helper method
- (NSMutableArray*) getMatchesFrom:(NSString*)data with:(NSString*)regex
{
NSRegularExpression *nsregexTest = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:nil];
NSArray *nsmatchesTest = [nsregexTest matchesInString:data options:0 range:NSMakeRange(0, [data length])];
NSMutableArray *arr = [NSMutableArray array];
for (NSTextCheckingResult *nsmatchTest in nsmatchesTest) {
NSMutableArray *localMatch = [NSMutableArray array];
for (NSUInteger i = 0, l = [nsmatchTest numberOfRanges]; i < l; i++) {
NSRange range = [nsmatchTest rangeAtIndex:i];
NSString *nsmatchStr = nil;
if (range.location != NSNotFound && NSMaxRange(range) <= [data length]) {
nsmatchStr = [data substringWithRange:[nsmatchTest rangeAtIndex:i]];
}
else {
nsmatchStr = @"";
}
[localMatch addObject:nsmatchStr];
}
[arr addObject:localMatch];
}
return arr;
}
# pragma mark -
# pragma mark Handshake callbacks (NSURLConnectionDataDelegate)
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// check for server status code (http://gigliwood.com/weblog/Cocoa/Q__When_is_an_conne.html)
if ([response respondsToSelector:@selector(statusCode)]) {
int statusCode = [((NSHTTPURLResponse *)response) statusCode];
DEBUGLOG(@"didReceiveResponse() %i", statusCode);
if (statusCode >= 400) {
// stop connecting; no more delegate messages
[connection cancel];
NSString *error = [NSString stringWithFormat:NSLocalizedString(@"Server returned status code %d", @""), statusCode];
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:error forKey:NSLocalizedDescriptionKey];
NSError *statusError = [NSError errorWithDomain:SocketIOError
code:statusCode
userInfo:errorInfo];
// call error callback manually
[self connection:connection didFailWithError:statusError];
}
}
[_httpRequestData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_httpRequestData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR: handshake failed ... %@", [error localizedDescription]);
_isConnected = NO;
_isConnecting = NO;
if ([_delegate respondsToSelector:@selector(socketIOHandshakeFailed:)]) {
[_delegate socketIOHandshakeFailed:self];
}
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:_httpRequestData encoding:NSASCIIStringEncoding];
DEBUGLOG(@"connectionDidFinishLoading() %@", responseString);
NSArray *data = [responseString componentsSeparatedByString:@":"];
// should be SID : heartbeat timeout : connection timeout : supported transports
// check each returned value (thanks for the input https://github.com/taiyangc)
BOOL connectionFailed = false;
_sid = [data objectAtIndex:0];
if ([_sid length] < 1 || [data count] < 4) {
// did not receive valid data, possibly missing a useSecure?
connectionFailed = true;
}
// check SID
DEBUGLOG(@"sid: %@", _sid);
NSString *regex = @"[^0-9]";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([_sid rangeOfString:@"error"].location != NSNotFound || [regexTest evaluateWithObject:_sid]) {
[self connectToHost:_host onPort:_port withParams:_params withNamespace:_endpoint];
return;
}
// check heartbeat timeout
_heartbeatTimeout = [[data objectAtIndex:1] floatValue];
if (_heartbeatTimeout == 0.0) {
// couldn't find float value -> fail
connectionFailed = true;
}
else {
// add small buffer of 7sec (magic xD)
_heartbeatTimeout += 7.0;
}
DEBUGLOG(@"heartbeatTimeout: %f", _heartbeatTimeout);
// index 2 => connection timeout
// get transports
NSString *t = [data objectAtIndex:3];
NSArray *transports = [t componentsSeparatedByString:@","];
DEBUGLOG(@"transports: %@", transports);
// TODO: check which transports are supported by the server
// if connection didn't return the values we need -> fail
if (connectionFailed) {
NSError* error;
error = [NSError errorWithDomain:SocketIOError
code:SocketIOServerRespondedWithInvalidConnectionData
userInfo:nil];
if ([_delegate respondsToSelector:@selector(socketIO:failedToConnectWithError:)]) {
[_delegate socketIO:self failedToConnectWithError:error];
}
// make sure to do call all cleanup code
[self onDisconnect:error];
return;
}
// if websocket
[self openSocket];
// TODO: if xhr ...
}
#if DEBUG_CERTIFICATE
// to deal with self-signed certificates
- (BOOL) connection:(NSURLConnection *)connection
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void) connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod
isEqualToString:NSURLAuthenticationMethodServerTrust]) {
// we only trust our own domain
if ([challenge.protectionSpace.host isEqualToString:_host]) {
SecTrustRef trust = challenge.protectionSpace.serverTrust;
NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
#endif
# pragma mark -
# pragma mark WebSocket Delegate Methods
- (void) webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
[self onData:message];
}
- (void) webSocketDidOpen:(SRWebSocket *)webSocket
{
DEBUGLOG(@"Socket opened.");
}
- (void) webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
DEBUGLOG(@"Socket failed with error ... %@", [error localizedDescription]);
// Assuming this resulted in a disconnect
[self onDisconnect:error];
}
- (void) webSocket:(SRWebSocket *)webSocket
didCloseWithCode:(NSInteger)code
reason:(NSString *)reason
wasClean:(BOOL)wasClean
{
DEBUGLOG(@"Socket closed.");
[self onDisconnect:[NSError errorWithDomain:SocketIOError
code:SocketIOWebSocketClosed
userInfo:nil]];
}
# pragma mark -
- (void) dealloc
{
_host = nil;
_sid = nil;
_endpoint = nil;
_webSocket = nil;
[_timeout invalidate];
_timeout = nil;
_queue = nil;
_acks = nil;
}
@end
# pragma mark -
# pragma mark SocketIOPacket implementation
@implementation SocketIOPacket
@synthesize type, pId, name, ack, data, args, endpoint;
- (id) init
{
self = [super init];
if (self) {
_types = [NSArray arrayWithObjects: @"disconnect",
@"connect",
@"heartbeat",
@"message",
@"json",
@"event",
@"ack",
@"error",
@"noop",
nil];
}
return self;
}
- (id) initWithType:(NSString *)packetType
{
self = [self init];
if (self) {
self.type = packetType;
}
return self;
}
- (id) initWithTypeIndex:(int)index
{
self = [self init];
if (self) {
self.type = [self typeForIndex:index];
}
return self;
}
- (id) dataAsJSON
{
if (self.data) {
NSData *utf8Data = [self.data dataUsingEncoding:NSUTF8StringEncoding];
return [SocketIOJSONSerialization objectFromJSONData:utf8Data error:nil];
}
else {
return nil;
}
}
- (NSNumber *) typeAsNumber
{
NSUInteger index = [_types indexOfObject:self.type];
NSNumber *num = [NSNumber numberWithUnsignedInteger:index];
return num;
}
- (NSString *) typeForIndex:(int)index
{
return [_types objectAtIndex:index];
}
- (void) dealloc
{
_types = nil;
type = nil;
pId = nil;
name = nil;
ack = nil;
data = nil;
args = nil;
endpoint = nil;
}
@end