-
Notifications
You must be signed in to change notification settings - Fork 129
/
IdSocketIOHandling.pas
1849 lines (1659 loc) · 53.2 KB
/
IdSocketIOHandling.pas
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit IdSocketIOHandling;
interface
{$I wsdefines.pas}
uses
windows, SyncObjs, SysUtils, StrUtils, Classes, Generics.Collections
{$IFDEF SUPEROBJECT}
, superobject
{$ENDIF}
, IdContext
, IdException
, IdHTTP
//
, IdServerBaseHandling
, IdIOHandlerWebsocket
;
type
{$IFNDEF SUPEROBJECT}
TSuperArray = String;
{$ENDIF}
TSocketIOContext = class;
TSocketIOCallbackObj = class;
TIdBaseSocketIOHandling = class;
TIdSocketIOHandling = class;
ISocketIOContext = interface;
ISocketIOCallback = interface;
TSocketIOMsg = reference to procedure(const ASocket: ISocketIOContext; const aText: string; const aCallback: ISocketIOCallback);
{$IFDEF SUPEROBJECT}
TSocketIOMsgJSON = reference to procedure(const ASocket: ISocketIOContext; const aJSON: ISuperObject; const aCallback: ISocketIOCallback);
{$ELSE}
TSocketIOMsgJSON = reference to procedure(const ASocket: ISocketIOContext; const aJSON:string; const aCallback: ISocketIOCallback);
{$ENDIF}
TSocketIOEvent = reference to procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback);
TSocketIONotify = reference to procedure(const ASocket: ISocketIOContext);
TSocketIOError = reference to procedure(const ASocket: ISocketIOContext; const aErrorClass, aErrorMessage: string);
TSocketIOEventError = reference to procedure(const ASocket: ISocketIOContext; const aCallback: ISocketIOCallback; E: Exception);
TSocketIONotifyList = class(TList<TSocketIONotify>);
TSocketIOEventList = class(TList<TSocketIOEvent>);
EIdSocketIoUnhandledMessage = class(EIdSilentException);
ISocketIOContext = interface
['{ACCAC678-054C-4D75-8BAD-5922F55623AB}']
function GetCustomData: TObject;
function GetOwnsCustomData: Boolean;
procedure SetCustomData(const Value: TObject);
procedure SetOwnsCustomData(const Value: Boolean);
property CustomData: TObject read GetCustomData write SetCustomData;
property OwnsCustomData: Boolean read GetOwnsCustomData write SetOwnsCustomData;
function ResourceName: string;
function PeerIP: string;
function PeerPort: Integer;
procedure Lock;
procedure UnLock;
function IsDisconnected: Boolean;
{$IFDEF SUPEROBJECT}
procedure EmitEvent(const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
procedure SendJSON(const aJSON: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
{$ENDIF}
procedure EmitEvent(const aEventName: string; const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
procedure Send(const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
end;
TSocketIOContext = class(TInterfacedObject,ISocketIOContext)
private
FLock: TCriticalSection;
FPingSend: Boolean;
FConnectSend: Boolean;
FGUID: string;
FPeerIP: string;
FCustomData: TObject;
FOwnsCustomData: Boolean;
procedure SetContext(const Value: TIdContext);
procedure SetConnectSend(const Value: Boolean);
procedure SetPingSend(const Value: Boolean);
function GetCustomData: TObject;
function GetOwnsCustomData: Boolean;
procedure SetCustomData(const Value: TObject);
procedure SetOwnsCustomData(const Value: Boolean);
protected
FHandling: TIdBaseSocketIOHandling;
FContext: TIdContext;
FIOHandler: TIdIOHandlerWebsocket;
FClient: TIdHTTP;
FEvent: TEvent;
FQueue: TList<string>;
FPendingMessages: TList<Int64>;
procedure QueueData(const aData: string);
procedure ServerContextDestroy(AContext: TIdContext);
public
constructor Create();overload;
constructor Create(aClient: TIdHTTP);overload;
procedure AfterConstruction; override;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
function WaitForQueue(aTimeout_ms: Integer): string;
function ResourceName: string;
function PeerIP: string;
function PeerPort: Integer;
function IsDisconnected: Boolean;
property GUID: string read FGUID;
property Context: TIdContext read FContext write SetContext;
property PingSend: Boolean read FPingSend write SetPingSend;
property ConnectSend: Boolean read FConnectSend write SetConnectSend;
property CustomData: TObject read GetCustomData write SetCustomData;
property OwnsCustomData: Boolean read GetOwnsCustomData write SetOwnsCustomData;
procedure EmitEvent(const aEventName: string; const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
procedure Send(const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
{$IFDEF SUPEROBJECT}
//todo: OnEvent per socket
//todo: store session info per connection (see Socket.IO Set + Get -> Storing data associated to a client)
//todo: namespace using "Of"
procedure EmitEvent(const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
procedure SendJSON(const aJSON: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
{$ENDIF}
end;
ISocketIOCallback = interface
['{BCC31817-7FD8-4CF6-B68B-0F9BAA80DF90}']
procedure SendResponse(const aResponse: string);
function IsResponseSend: Boolean;
end;
TSocketIOCallbackObj = class(TInterfacedObject,
ISocketIOCallback)
protected
FHandling: TIdBaseSocketIOHandling;
FSocket: ISocketIOContext;
FMsgNr: Integer;
{ISocketIOCallback}
procedure SendResponse(const aResponse: string);
function IsResponseSend: Boolean;
public
constructor Create(aHandling: TIdBaseSocketIOHandling; aSocket: ISocketIOContext; aMsgNr: Integer);
end;
TSocketIOPromise = class
protected
Done, Success: Boolean;
Error: Exception;
{$IFDEF SUPEROBJECT}
Data : ISuperObject;
{$ENDIF}
Event: TEvent;
public
procedure AfterConstruction; override;
destructor Destroy; override;
end;
ESocketIOException = class(Exception);
ESocketIOTimeout = class(ESocketIOException);
ESocketIODisconnect = class(ESocketIOException);
TIdBaseSocketIOHandling = class(TIdServerBaseHandling)
protected
FLock: TCriticalSection;
FConnections: TObjectDictionary<TIdContext,ISocketIOContext>;
FConnectionsGUID: TObjectDictionary<string,ISocketIOContext>;
FOnConnectionList,
FOnDisconnectList: TSocketIONotifyList;
FOnEventList: TObjectDictionary<string,TSocketIOEventList>;
FOnSocketIOMsg: TSocketIOMsg;
{$IFDEF SUPEROBJECT}
FOnSocketIOJson: TSocketIOMsgJSON;
{$ENDIF}
procedure ProcessEvent(const AContext: ISocketIOContext; const aText: string; aMsgNr: Integer; aHasCallback: Boolean);
private
FOnEventError: TSocketIOEventError;
protected
type
TSocketIOCallback = procedure(const aData: string) of object;
TSocketIOCallbackRef = reference to procedure(const aData: string);
var
FSocketIOMsgNr: Integer;
FSocketIOEventCallback: TDictionary<Integer,TSocketIOCallback>;
FSocketIOEventCallbackRef: TDictionary<Integer,TSocketIOCallbackRef>;
//FSocketIOEventPromises: TDictionary<Integer,TSocketIOPromise>;
FSocketIOErrorRef: TDictionary<Integer,TSocketIOError>;
function WriteConnect(const ASocket: ISocketIOContext): string; overload;
procedure WriteDisConnect(const ASocket: ISocketIOContext);overload;
procedure WritePing(const ASocket: ISocketIOContext);overload;
//
function WriteConnect(const AContext: TIdContext): string; overload;
procedure WriteDisConnect(const AContext: TIdContext);overload;
procedure WritePing(const AContext: TIdContext);overload;
procedure WriteSocketIOMsg(const ASocket: ISocketIOContext; const aRoom, aData: string; aCallback: TSocketIOCallbackRef = nil; const aOnError: TSocketIOError = nil);
procedure WriteSocketIOJSON(const ASocket: ISocketIOContext; const aRoom, aJSON: string; aCallback: TSocketIOCallbackRef = nil; const aOnError: TSocketIOError = nil);
procedure WriteSocketIOEvent(const ASocket: ISocketIOContext; const aRoom, aEventName, aJSONArray: string; aCallback: TSocketIOCallback; const aOnError: TSocketIOError);
procedure WriteSocketIOEventRef(const ASocket: ISocketIOContext; const aRoom, aEventName, aJSONArray: string; aCallback: TSocketIOCallbackRef; const aOnError: TSocketIOError);
{$IFDEF SUPEROBJECT}
function WriteSocketIOEventSync(const ASocket: ISocketIOContext; const aRoom, aEventName, aJSONArray: string; aMaxwait_ms: Cardinal = INFINITE): ISuperObject;
{$ENDIF}
procedure WriteSocketIOResult(const ASocket: ISocketIOContext; aRequestMsgNr: Integer; const aRoom, aData: string);
procedure ProcessSocketIO_XHR(const aGUID: string; const aStrmRequest, aStrmResponse: TStream);
procedure ProcessSocketIORequest(const ASocket: ISocketIOContext; const strmRequest: TMemoryStream);overload;
procedure ProcessSocketIORequest(const ASocket: ISocketIOContext; const aData: string);overload;
procedure ProcessSocketIORequest(const AContext: TIdContext; const strmRequest: TMemoryStream);overload;
procedure ProcessHeatbeatRequest(const ASocket: ISocketIOContext; const aText: string);virtual;
procedure ProcessCloseChannel(const ASocket: ISocketIOContext; const aChannel: string);virtual;
function WriteString(const ASocket: ISocketIOContext; const aText: string): string; virtual;
public
procedure AfterConstruction; override;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
function ConnectionCount: Integer;
function GetSocketIOContext(const AContext: TIdContext): ISocketIOContext;
// procedure EmitEventToAll(const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil);
function NewConnection(const AContext: TIdContext): ISocketIOContext;overload;
function NewConnection(const aGUID, aPeerIP: string): ISocketIOContext;overload;
procedure FreeConnection(const AContext: TIdContext);overload;
procedure FreeConnection(const ASocket: ISocketIOContext);overload;
property OnSocketIOMsg : TSocketIOMsg read FOnSocketIOMsg write FOnSocketIOMsg;
{$IFDEF SUPEROBJECT}
property OnSocketIOJson : TSocketIOMsgJSON read FOnSocketIOJson write FOnSocketIOJson;
{$ENDIF}
procedure OnEvent (const aEventName: string; const aCallback: TSocketIOEvent);
procedure OnConnection(const aCallback: TSocketIONotify);
procedure OnDisconnect(const aCallback: TSocketIONotify);
property OnEventError: TSocketIOEventError read FOnEventError write FOnEventError;
procedure EnumerateSockets(const aEachSocketCallback: TSocketIONotify);
end;
TIdSocketIOHandling = class(TIdBaseSocketIOHandling)
public
procedure Send(const aMessage: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
procedure Emit(const aEventName: string; const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
{$IFDEF SUPEROBJECT}
procedure Emit(const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
function EmitSync(const aEventName: string; const aData: ISuperObject; aMaxwait_ms: Cardinal = INFINITE): ISuperobject;
//procedure Emit(const aEventName: string; const aData: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
{$ENDIF}
end;
{$IFNDEF SUPEROBJECT}
function SO(const S:string):string; inline;
{$ENDIF}
implementation
uses
IdServerWebsocketContext, IdHTTPWebsocketClient;
{$IFNDEF SUPEROBJECT}
function SO(const S:string):string; inline;
begin
Result := S;
end;
{$ENDIF}
procedure TIdBaseSocketIOHandling.AfterConstruction;
begin
inherited;
FLock := TCriticalSection.Create;
FConnections := TObjectDictionary<TIdContext,ISocketIOContext>.Create([]);
FConnectionsGUID := TObjectDictionary<string,ISocketIOContext>.Create([]);
FOnConnectionList := TSocketIONotifyList.Create;
FOnDisconnectList := TSocketIONotifyList.Create;
FOnEventList := TObjectDictionary<string,TSocketIOEventList>.Create([doOwnsValues]);
FSocketIOEventCallback := TDictionary<Integer,TSocketIOCallback>.Create;
FSocketIOEventCallbackRef := TDictionary<Integer,TSocketIOCallbackRef>.Create;
FSocketIOErrorRef := TDictionary<Integer,TSocketIOError>.Create;
//FSocketIOEventPromises := TDictionary<Integer,TSocketIOPromise>.Create;
end;
function TIdBaseSocketIOHandling.ConnectionCount: Integer;
var
context: ISocketIOContext;
begin
Lock;
try
Result := 0;
//note: is single connection?
for context in FConnections.Values do
begin
if context.IsDisconnected then Continue;
Inc(Result);
end;
for context in FConnectionsGUID.Values do
begin
if context.IsDisconnected then Continue;
Inc(Result);
end;
finally
UnLock;
end;
end;
destructor TIdBaseSocketIOHandling.Destroy;
var squid: string;
idcontext: TIdContext;
begin
Lock;
FSocketIOEventCallback.Free;
FSocketIOEventCallbackRef.Free;
FSocketIOErrorRef.Free;
//FSocketIOEventPromises.Free;
FOnEventList.Free;
FOnConnectionList.Free;
FOnDisconnectList.Free;
while FConnections.Count > 0 do
for idcontext in FConnections.Keys do
begin
//FConnections.Items[idcontext]._Release;
FConnections.ExtractPair(idcontext);
end;
while FConnectionsGUID.Count > 0 do
for squid in FConnectionsGUID.Keys do
begin
//FConnectionsGUID.Items[squid]._Release;
FConnectionsGUID.ExtractPair(squid);
end;
FConnections.Free;
FConnections := nil;
FConnectionsGUID.Free;
UnLock;
FLock.Free;
inherited;
end;
procedure TIdBaseSocketIOHandling.EnumerateSockets(
const aEachSocketCallback: TSocketIONotify);
var socket: ISocketIOContext;
begin
Assert(Assigned(aEachSocketCallback));
Lock;
try
for socket in FConnections.Values do
try
aEachSocketCallback(socket);
except
//continue: e.g. connnection closed etc
end;
for socket in FConnectionsGUID.Values do
try
aEachSocketCallback(socket);
except
//continue: e.g. connnection closed etc
end;
finally
Unlock;
end;
end;
procedure TIdBaseSocketIOHandling.FreeConnection(
const ASocket: ISocketIOContext);
var squid: string;
idcontext: TIdContext;
errorref: TSocketIOError;
i: Integer;
begin
if ASocket = nil then Exit;
Lock;
try
with TSocketIOContext(ASocket) do
begin
Context := nil;
FIOHandler := nil;
FClient := nil;
FHandling := nil;
FGUID := '';
FPeerIP := '';
end;
for idcontext in FConnections.Keys do
begin
if FConnections.Items[idcontext] = ASocket then
begin
FConnections.ExtractPair(idcontext);
//ASocket._Release;
end;
end;
for squid in FConnectionsGUID.Keys do
begin
if FConnectionsGUID.Items[squid] = ASocket then
begin
FConnectionsGUID.ExtractPair(squid);
//ASocket._Release; //use reference count? otherwise AV when used in TThread.Queue
end;
end;
//pending callbacks? then exceute error messages
for i in TSocketIOContext(ASocket).FPendingMessages do
begin
FSocketIOEventCallback.Remove(i);
FSocketIOEventCallbackRef.Remove(i);
if FSocketIOErrorRef.TryGetValue(i, errorref) then
begin
FSocketIOErrorRef.Remove(i);
try
errorref(ASocket, ESocketIODisconnect.ClassName, 'Connection disconnected');
except
end;
end;
end;
finally
Unlock;
end;
end;
function TIdBaseSocketIOHandling.GetSocketIOContext(const AContext: TIdContext): ISocketIOContext;
var
socket: ISocketIOContext;
begin
Result := nil;
Lock;
try
if FConnections.TryGetValue(AContext, socket) then
Exit(socket);
finally
UnLock;
end;
end;
procedure TIdBaseSocketIOHandling.FreeConnection(const AContext: TIdContext);
var
socket: ISocketIOContext;
begin
Lock;
try
if FConnections.TryGetValue(AContext, socket) then
FreeConnection(socket);
finally
UnLock;
end;
end;
procedure TIdBaseSocketIOHandling.Lock;
begin
// Assert(FConnections <> nil);
// System.TMonitor.Enter(Self);
FLock.Enter;
end;
function TIdBaseSocketIOHandling.NewConnection(
const AGUID, aPeerIP: string): ISocketIOContext;
var
socket: TSocketIOContext;
begin
Lock;
try
if not FConnectionsGUID.TryGetValue(AGUID, Result) then
begin
socket := TSocketIOContext.Create;
FConnectionsGUID.Add(AGUID, socket);
end
else
socket := TSocketIOContext(Result);
//socket.Context := AContext;
socket.FGUID := AGUID;
if aPeerIP <> '' then
socket.FPeerIP := aPeerIP;
socket.FHandling := Self;
socket.FConnectSend := False;
socket.FPingSend := False;
Result := socket;
finally
UnLock;
end;
end;
function TIdBaseSocketIOHandling.NewConnection(const AContext: TIdContext): ISocketIOContext;
var
socket: TSocketIOContext;
begin
Lock;
try
if not FConnections.TryGetValue(AContext, Result) then
begin
socket := TSocketIOContext.Create;
FConnections.Add(AContext, socket);
end
else
socket := TSocketIOContext(Result);
socket.Context := AContext;
socket.FHandling := Self;
socket.FConnectSend := False;
socket.FPingSend := False;
Result := socket;
finally
UnLock;
end;
end;
procedure TIdBaseSocketIOHandling.OnConnection(const aCallback: TSocketIONotify);
var context: ISocketIOContext;
begin
FOnConnectionList.Add(aCallback);
Lock;
try
for context in FConnections.Values do
aCallback(context);
for context in FConnectionsGUID.Values do
aCallback(context);
finally
UnLock;
end;
end;
procedure TIdBaseSocketIOHandling.OnDisconnect(const aCallback: TSocketIONotify);
begin
FOnDisconnectList.Add(aCallback);
end;
procedure TIdBaseSocketIOHandling.OnEvent(const aEventName: string; const aCallback: TSocketIOEvent);
var list: TSocketIOEventList;
begin
if not FOnEventList.TryGetValue(aEventName, list) then
begin
list := TSocketIOEventList.Create;
FOnEventList.Add(aEventName, list);
end;
list.Add(aCallback);
end;
procedure TIdBaseSocketIOHandling.ProcessCloseChannel(
const ASocket: ISocketIOContext; const aChannel: string);
begin
if aChannel <> '' then
//todo: close channel
else if (TSocketIOContext(ASocket).FContext <> nil) then
TSocketIOContext(ASocket).FContext.Connection.Disconnect;
end;
procedure TIdBaseSocketIOHandling.ProcessEvent(const AContext: ISocketIOContext; const aText: string; aMsgNr: Integer;aHasCallback: Boolean);
var
name: string;
{$IFNDEF SUPEROBJECT}
args: string;
{$ELSE}
args: TSuperArray;
json: ISuperObject;
// socket: TSocketIOContext;
{$ENDIF}
list: TSocketIOEventList;
event: TSocketIOEvent;
callback: ISocketIOCallback;
{$IFNDEF SUPEROBJECT}
function _GetJsonMember(const aText:string; const iName:string):string;
var xs,xe,ctn:Integer;
begin
// Based on json formated content
Result := '';
xs := Pos('"'+iName+'"',aText);
if xs=0 then Exit;
xs := PosEx(':',aText,xs);
if xs=0 then Exit;
//
inc(xs);
while (xs<=length(aText)) and (aText[xs] in [' ',#13,#10,#8,#9]) do inc(xs);
if xs>=length(aText) then Exit;
//
if aText[xs]='[' then
begin
xe := xs+1; ctn := 1;
while (xe<=length(aText)) do
begin
if aText[xe]='[' then inc(ctn);
if aText[xe]=']' then dec(ctn);
if ctn=0 then break;
inc(xe);
end;
if ctn=0 then
Result := Copy(aText,xs,xe-xs+1);
end
else
if aText[xs]='{' then
begin
xe := xs+1; ctn := 1;
while (xe<=length(aText)) do
begin
if aText[xe]='{' then inc(ctn);
if aText[xe]='}' then dec(ctn);
if ctn=0 then break;
inc(xe);
end;
if ctn=0 then
Result := Copy(aText,xs,xe-xs+1);
end
else
if aText[xs]='"' then
begin
xe := PosEx('"',aText,xs+1);
if xe=0 then Exit;
Result := Copy(aText,xs+1,xe-xs-1);
end;
end;
{$ENDIF}
begin
//'5:' [message id ('+')] ':' [message endpoint] ':' [json encoded event]
//5::/chat:{"name":"my other event","args":[{"my":"data"}]}
//5:1+:/chat:{"name":"GetLocations","args":[""]}
{$IFNDEF SUPEROBJECT}
name := _GetJsonMember(aText,'name'); //"my other event
args := _GetJsonMember(aText,'args'); //[{"my":"data"}]
{$ELSE}
json := SO(aText);
// args := nil;
try
name := json.S['name']; //"my other event
args := json.A['args']; //[{"my":"data"}]
{$ENDIF}
if FOnEventList.TryGetValue(name, list) then
begin
if list.Count = 0 then
raise EIdSocketIoUnhandledMessage.Create(aText);
// socket := FConnections.Items[AContext];
if aHasCallback then
callback := TSocketIOCallbackObj.Create(Self, AContext, aMsgNr)
else
callback := nil;
try
for event in list do
try
event(AContext, args, callback);
except on E:Exception do
if Assigned(OnEventError) then
OnEventError(AContext, callback, e)
else
if callback <> nil then
{$IFNDEF SUPEROBJECT}
callback.SendResponse('Error');
{$ELSE}
callback.SendResponse( SO(['Error', SO(['msg', e.message])]).AsJSon );
{$ENDIF}
end;
finally
callback := nil;
end;
end
else
raise EIdSocketIoUnhandledMessage.Create(aText);
{$IFDEF SUPEROBJECT}
finally
//args.Free;
json := nil;
end;
{$ENDIF}
end;
procedure TIdBaseSocketIOHandling.ProcessHeatbeatRequest(const ASocket: ISocketIOContext; const aText: string);
begin
with TSocketIOContext(ASocket) do
begin
if PingSend then
PingSend := False //reset, client responded with 2:: heartbeat too
else
begin
PingSend := True; //stop infinite ping response loops
WriteString(ASocket, aText); //write same connect back, e.g. 2::
end;
end;
end;
procedure TIdBaseSocketIOHandling.ProcessSocketIORequest(
const ASocket: ISocketIOContext; const strmRequest: TMemoryStream);
function __ReadToEnd: string;
var
utf8: TBytes;
ilength: Integer;
begin
Result := '';
ilength := strmRequest.Size - strmRequest.Position;
if ilength <= 0 then
Exit;
SetLength(utf8, ilength);
strmRequest.Read(utf8[0], ilength);
Result := TEncoding.UTF8.GetString(utf8);
end;
var str: string;
begin
str := __ReadToEnd;
ProcessSocketIORequest(ASocket, str);
end;
procedure TIdBaseSocketIOHandling.ProcessSocketIORequest(const AContext: TIdContext;
const strmRequest: TMemoryStream);
var
socket: ISocketIOContext;
begin
if not FConnections.TryGetValue(AContext, socket) then
begin
socket := NewConnection(AContext);
end;
ProcessSocketIORequest(socket, strmRequest);
end;
procedure TIdBaseSocketIOHandling.ProcessSocketIO_XHR(const aGUID: string; // const AContext: TIdContext;
const aStrmRequest, aStrmResponse: TStream);
var
socket: ISocketIOContext;
sdata: string;
i, ilength: Integer;
bytes, singlemsg: TBytes;
begin
if not FConnectionsGUID.TryGetValue(aGUID, socket) or
socket.IsDisconnected
then
socket := NewConnection(aGUID, '');
if not TSocketIOContext(socket).FConnectSend then
WriteConnect(socket);
if (aStrmRequest <> nil) and
(aStrmRequest.Size > 0) then
begin
aStrmRequest.Position := 0;
SetLength(bytes, aStrmRequest.Size);
aStrmRequest.Read(bytes[0], aStrmRequest.Size);
if (Length(bytes) > 3) and
(bytes[0] = 239) and (bytes[1] = 191) and (bytes[2] = 189) then
begin
//io.parser.encodePayload(msgs)
//'\ufffd' + packet.length + '\ufffd'
//'�17�3:::singlemessage�52�5:4+::{"name":"registerScanner","args":["scanner1"]}'
while bytes <> nil do
begin
i := 3;
//search second '\ufffd'
while not ( (bytes[i+0] = 239) and (bytes[i+1] = 191) and (bytes[i+2] = 189) ) do
begin
Inc(i);
if i+2 > High(bytes) then Exit; //wrong data
end;
//get data between
ilength := StrToInt( TEncoding.UTF8.GetString(bytes, 3, i-3) ); //17
singlemsg := Copy(bytes, i+3, ilength);
bytes := Copy(bytes, i+3 + ilength, Length(bytes));
sdata := TEncoding.UTF8.GetString(singlemsg); //3:::singlemessage
try
ProcessSocketIORequest(socket, sdata);
except
//next
end;
end;
end
else
begin
sdata := TEncoding.UTF8.GetString(bytes);
ProcessSocketIORequest(socket, sdata);
end;
end;
//e.g. POST, no GET?
if aStrmResponse = nil then Exit;
//wait till some response data to be send (long polling)
sdata := TSocketIOContext(socket).WaitForQueue(5 * 1000);
if sdata = '' then
begin
//no data? then send ping
WritePing(socket);
sdata := TSocketIOContext(socket).WaitForQueue(0);
end;
//send response back
if sdata <> '' then
begin
{$WARN SYMBOL_PLATFORM OFF}
// if DebugHook <> 0 then
// Windows.OutputDebugString(PChar('Send: ' + sdata));
bytes := TEncoding.UTF8.GetBytes(sdata);
aStrmResponse.Write(bytes[0], Length(bytes));
end;
end;
procedure TIdBaseSocketIOHandling.UnLock;
begin
//System.TMonitor.Exit(Self);
FLock.Leave;
end;
procedure TIdBaseSocketIOHandling.ProcessSocketIORequest(
const ASocket: ISocketIOContext; const aData: string);
function __GetSocketIOPart(const aData: string; aIndex: Integer): string;
var ipos: Integer;
i: Integer;
begin
//'5::/chat:{"name":"hi!"}'
//0 = 5
//1 =
//2 = /chat
//3 = {"name":"hi!"}
ipos := 0;
for i := 0 to aIndex-1 do
ipos := PosEx(':', aData, ipos+1);
if ipos >= 0 then
begin
Result := Copy(aData, ipos+1, Length(aData));
if aIndex < 3 then // /chat:{"name":"hi!"}'
begin
ipos := PosEx(':', Result, 1); // :{"name":"hi!"}'
if ipos > 0 then
Result := Copy(Result, 1, ipos-1); // /chat
end;
end;
end;
var
str, smsg, schannel, sdata: string;
imsg: Integer;
bCallback: Boolean;
// socket: TSocketIOContext;
callback: TSocketIOCallback;
callbackref: TSocketIOCallbackRef;
callbackobj: ISocketIOCallback;
errorref: TSocketIOError;
{$IFDEF SUPEROBJECT}
error: ISuperObject;
{$ENDIF}
socket: TSocketIOContext;
begin
if ASocket = nil then Exit;
socket := ASocket as TSocketIOContext;
if not FConnections.ContainsValue(socket) and
not FConnectionsGUID.ContainsValue(socket) then
begin
Lock;
try
//ASocket._AddRef;
FConnections.Add(nil, socket); //clients do not have a TIdContext?
finally
UnLock;
end;
end;
str := aData;
if str = '' then Exit;
// if DebugHook <> 0 then
// Windows.OutputDebugString(PChar('Received: ' + str));
while str[1] = #0 do
Delete(str, 1, 1);
//5:1+:/chat:test
smsg := __GetSocketIOPart(str, 1);
imsg := 0;
bCallback := False;
if smsg <> '' then // 1+
begin
imsg := StrToIntDef(ReplaceStr(smsg,'+',''), 0); // 1
bCallback := (Pos('+', smsg) > 1); //trailing +, e.g. 1+
end;
schannel := __GetSocketIOPart(str, 2); // /chat
sdata := __GetSocketIOPart(str, 3); // test
//(0) Disconnect
if StartsStr('0:', str) then
begin
schannel := __GetSocketIOPart(str, 2);
ProcessCloseChannel(socket, schannel);
end
//(1) Connect
//'1::' [path] [query]
else if StartsStr('1:', str) then
begin
//todo: add channel/room to authorized channel/room list
if not socket.ConnectSend then
WriteString(socket, str); //write same connect back, e.g. 1::/chat
end
//(2) Heartbeat
else if StartsStr('2:', str) then
begin
//todo: timer to disconnect client if no ping within time
ProcessHeatbeatRequest(socket, str);
end
//(3) Message (https://github.com/LearnBoost/socket.io-spec#3-message)
//'3:' [message id ('+')] ':' [message endpoint] ':' [data]
//3::/chat:hi
else if StartsStr('3:', str) then
begin
if Assigned(OnSocketIOMsg) then
begin
if bCallback then
begin
callbackobj := TSocketIOCallbackObj.Create(Self, socket, imsg);
try
try
OnSocketIOMsg(socket, sdata, callbackobj); //, imsg, bCallback);
except
on E:Exception do
begin
{$IFDEF SUPEROBJECT}
if not callbackobj.IsResponseSend then
callbackobj.SendResponse( SO(['Error', SO(['Type', e.ClassName, 'Message', e.Message])]).AsJSon );
{$ELSE}
//TODO
{$ENDIF}
end;
end;
finally
callbackobj := nil;
end
end
else
OnSocketIOMsg(ASocket, sdata, nil);
end
else
raise EIdSocketIoUnhandledMessage.Create(str);
end
//(4) JSON Message
//'4:' [message id ('+')] ':' [message endpoint] ':' [json]
//4:1::{"a":"b"}
else if StartsStr('4:', str) then
begin
{$IFDEF SUPEROBJECT}
if Assigned(OnSocketIOJson) then
begin
if bCallback then
begin
callbackobj := TSocketIOCallbackObj.Create(Self, socket, imsg);
try
try
OnSocketIOJson(socket, SO(sdata), callbackobj); //, imsg, bCallback);
except
on E:Exception do
begin
if not callbackobj.IsResponseSend then
callbackobj.SendResponse( SO(['Error', SO(['Type', e.ClassName, 'Message', e.Message])]).AsJSon );
end;
end;
finally
callbackobj := nil;
end
end
else
OnSocketIOJson(ASocket, SO(sdata), nil); //, imsg, bCallback);
end
else
{$ENDIF}
raise EIdSocketIoUnhandledMessage.Create(str);
end
//(5) Event
//'5:' [message id ('+')] ':' [message endpoint] ':' [json encoded event]
//5::/chat:{"name":"my other event","args":[{"my":"data"}]}
//5:1+:/chat:{"name":"GetLocations","args":[""]}
else if StartsStr('5:', str) then
begin
//if Assigned(OnSocketIOEvent) then
// OnSocketIOEvent(AContext, sdata, imsg, bCallback);
try
ProcessEvent(socket, sdata, imsg, bCallback);
except
on e:exception do
//
end
end
//(6) ACK
//6::/news:1+["callback"]
//6:::1+["Response"]
else if StartsStr('6:', str) then
begin