-
Notifications
You must be signed in to change notification settings - Fork 16
/
DataPortIP.pas
765 lines (684 loc) · 20.4 KB
/
DataPortIP.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
{
Asynchronous wrapper around Synapse TBlockSocket.
(C) Sergey Bodrov, 2012-2018
When using UDP, remember, that it not session protocol, data delivery and correct
order not guaranteed. To start receive data, you must send empty packet to
remote side, it tell remote side return address.
From version 1.0.3 multiple DataPortIP instances uses common socket reader with single thread.
Properties:
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
LocalHost - IP-address or name of local host
LocalPort - local UPD or TCP port number
Methods:
Open() - Connect to remote port. Session establiched for TCP and just port initialised for UDP. Init string format:
InitStr = 'RemoteHost:RemotePort'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number
Events:
OnOpen - Triggered after UDP port init or TCP session establiched.
}
unit DataPortIP;
interface
uses {$ifndef FPC}Windows,{$endif} SysUtils, Classes,
syncobjs, DataPort, synsock, blcksock, synautil;
{$ifdef Linux}
// Uncomment next line to enable TCP keep-alive in Linux
//{$define LINUX_TCP_KEEPALIVE}
{$endif}
type
TIpProtocolEnum = (ippUDP, ippTCP);
TIpSocketItem = class;
{ TDataPortIP }
TDataPortIP = class(TDataPort)
private
//slReadData: TStringList; // for storing every incoming data packet separately
FLock: TMultiReadExclusiveWriteSynchronizer;
procedure SetIpProtocol(AValue: TIpProtocolEnum);
protected
FIpSocketItem: TIpSocketItem;
FRemoteHost: string;
FRemotePort: string;
FIpProtocol: TIpProtocolEnum;
function GetLocalHost: string; virtual;
function GetLocalPort: string; virtual;
procedure OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
procedure OnErrorHandler(Sender: TObject; const AMsg: string);
procedure OnConnectHandler(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open() - Connect to remote port. Session establiched for TCP and just port initialised for UDP. Init string format:
InitStr = 'RemoteHost:RemotePort'
RemoteHost - IP-address or name of remote host
RemotePort - remote UPD or TCP port number }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): boolean; override;
function Pull(ASize: Integer = MaxInt): AnsiString; override;
function Peek(ASize: Integer = MaxInt): AnsiString; override;
function PeekSize(): Cardinal; override;
{ IP protocol type }
property IpProtocol: TIpProtocolEnum read FIpProtocol write SetIpProtocol;
published
{ IP-address or name of remote host }
property RemoteHost: string read FRemoteHost write FRemoteHost;
{ remote UPD or TCP port number }
property RemotePort: string read FRemotePort write FRemotePort;
{ IP-address or name of local host }
property LocalHost: string read GetLocalHost;
{ local UPD or TCP port number }
property LocalPort: string read GetLocalPort;
property Active;
property OnDataAppear;
property OnError;
{ Triggered after UDP port init or TCP session establiched }
property OnOpen;
property OnClose;
end;
TDataPortTCP = class(TDataPortIP)
public
procedure Open(const AInitStr: string = ''); override;
end;
{ TDataPortUDP }
TDataPortUDP = class(TDataPortIP)
public
procedure Open(const AInitStr: string = ''); override;
{ Send data to destination address ADestAddr as 'host:port' }
function PushTo(const AData: AnsiString; ADestAddr: string): Boolean;
end;
{ TIpSocketItem }
{ Item for sockets list, created on Open(), used by reader thread }
TIpSocketItem = class(TObject)
private
FOnIncomingMsg: TMsgEvent;
FOnError: TMsgEvent;
FOnConnect: TNotifyEvent;
FLock: TCriticalSection;
public
// Only socket reader can manage Socket
Socket: TBlockSocket;
DataPortIP: TDataPortIP;
Protocol: TIpProtocolEnum;
LockCount: Integer;
RxDataStr: AnsiString;
//TxDataStr: AnsiString;
ErrorStr: string;
Active: Boolean;
Connected: Boolean;
function GetLocalHost(): string;
function GetLocalPort(): string;
function SendString(const ADataStr: AnsiString): Boolean;
function SendStream(st: TStream): Boolean;
property Lock: TCriticalSection read FLock;
property OnIncomingMsg: TMsgEvent read FOnIncomingMsg write FOnIncomingMsg;
property OnError: TMsgEvent read FOnError write FOnError;
property OnConnect: TNotifyEvent read FOnConnect write FOnConnect;
end;
procedure Register;
implementation
type
{ TIpSocketPool }
{ For better portability to DLL and stability, reader thread and critical section
automaticaly created after unit initialisation, when first DataPortIP opened.
And destroyed when last DataPortIP closed, before unit finalisation. }
TIpSocketPool = class(TList)
private
FIpReadThread: TThread;
FLock: TCriticalSection;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
procedure BeforeDestruction(); override;
function DataPortOpen(ADataPortIP: TDataPortIP; AIncomingMsgHandler: TMsgEvent; AErrorHandler: TMsgEvent; AConnectHandler: TNotifyEvent): TIpSocketItem;
procedure DataPortClose(ADataPortIP: TDataPortIP);
function GetItem(AIndex: Integer): TIpSocketItem;
{ Lock for modifing items list. NOTE! Can be nil if no items in list! }
property Lock: TCriticalSection read FLock;
end;
{ TIpReadThread }
TIpReadThread = class(TThread)
protected
FItem: TIpSocketItem;
FEventType: Byte; // 0 - none, 1-connect, 2-data, 3-error
procedure CloseSocket();
procedure Execute(); override;
procedure SyncProc();
public
IpSocketPool: TIpSocketPool;
end;
var
GlobalIpSocketPool: TIpSocketPool;
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortTCP]);
RegisterComponents('DataPort', [TDataPortUDP]);
end;
{ TIpReadThread }
procedure TIpReadThread.CloseSocket();
begin
FItem.Active := False;
if Assigned(FItem.Socket) then
begin
try
FItem.Socket.CloseSocket();
finally
FreeAndNil(FItem.Socket);
end;
end;
end;
procedure TIpReadThread.Execute();
var
n, ItemLockCount: Integer;
{$ifdef LINUX_TCP_KEEPALIVE}OptVal: Integer;{$endif}
IsNeedSleep: Boolean;
begin
n := 0;
while not Terminated do
begin
IsNeedSleep := True;
if n < IpSocketPool.Count then
begin
FItem := IpSocketPool.GetItem(n);
if Assigned(FItem.DataPortIP) then
begin
// acquire lock
//ItemLockCount := InterLockedIncrement(FItem.LockCount);
try
//if (ItemLockCount = 1) then
begin
// connect
if FItem.Active and (not Assigned(FItem.Socket)) then
begin
FItem.Connected := False;
FItem.ErrorStr := '';
case FItem.DataPortIP.IpProtocol of
ippUDP: FItem.Socket := TUDPBlockSocket.Create();
ippTCP: FItem.Socket := TTCPBlockSocket.Create();
end;
FItem.Socket.Connect(FItem.DataPortIP.RemoteHost, FItem.DataPortIP.RemotePort);
if FItem.Socket.LastError <> 0 then
begin
// Error event
FItem.ErrorStr := IntToStr(FItem.Socket.LastError) + ' ' + FItem.Socket.LastErrorDesc;
FItem.Active := False;
end
else
begin
// Connected event
FItem.Connected := True;
if Assigned(FItem.OnConnect) then
begin
FEventType := 1;
Synchronize(SyncProc);
end;
{$ifdef LINUX_TCP_KEEPALIVE}
// Set TCP keep-alive for Linux
OptVal := 1;
SetSockOpt(FItem.Socket.Socket, SOL_SOCKET, SO_KEEPALIVE, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPIDLE - Start keepalives after this period
SetSockOpt(FItem.Socket.Socket, 6, 4, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPINTVL - Interval between keepalives
SetSockOpt(FItem.Socket.Socket, 6, 5, @OptVal, SizeOf(OptVal));
OptVal := 3; // TCP_KEEPCNT - Number of keepalives before death
SetSockOpt(FItem.Socket.Socket, 6, 6, @OptVal, SizeOf(OptVal));
{$endif}
end;
//IsNeedSleep := False;
end;
// read
//if FItem.Active and Assigned(FItem.Socket) and (FItem.Socket.WaitingData > 0) then
//if FItem.Active and Assigned(FItem.Socket) and (FItem.Socket.WaitingDataEx() > 0) then
if FItem.Active and Assigned(FItem.Socket) then
begin
try
FItem.RxDataStr := FItem.RxDataStr + FItem.Socket.RecvPacket(0);
if FItem.Socket.LastError = 0 then
begin
// DataRead event
if Assigned(FItem.OnIncomingMsg) then
begin
FEventType := 2;
Synchronize(SyncProc);
end;
end
else if FItem.Socket.LastError = WSAETIMEDOUT then
begin
// nothing
end
else
begin
// Error event
FItem.ErrorStr := IntToStr(FItem.Socket.LastError) + ' ' + FItem.Socket.LastErrorDesc;
FItem.Active := False;
end;
IsNeedSleep := False;
except on E: Exception do
begin
FItem.ErrorStr := E.Message;
CloseSocket();
end;
end;
end;
// disconnect
if (not FItem.Active) and Assigned(FItem.Socket) then
begin
CloseSocket();
IsNeedSleep := False;
end;
end;
finally
// release lock
//InterLockedDecrement(FItem.LockCount);
end;
end
else
begin
// delete item
CloseSocket();
if Assigned(IpSocketPool.Lock) then
begin
IpSocketPool.Lock.Acquire();
try
IpSocketPool.Delete(n);
Dec(n);
finally
IpSocketPool.Lock.Release();
end;
end;
end;
// Error event
if FItem.ErrorStr <> '' then
begin
if Assigned(FItem.OnError) then
begin
FEventType := 3;
Synchronize(SyncProc);
end;
FItem.ErrorStr := '';
end;
Inc(n);
end
else
begin
n := 0;
if IsNeedSleep then
Sleep(1);
end;
end;
if Terminated then
begin
// cleanup sockets
for n := IpSocketPool.Count-1 downto 0 do
begin
FItem := IpSocketPool.GetItem(n);
CloseSocket();
IpSocketPool.Delete(n);
end;
end;
end;
procedure TIpReadThread.SyncProc();
begin
case FEventType of
1: FItem.OnConnect(FItem);
2: FItem.OnIncomingMsg(FItem, FItem.RxDataStr);
3: FItem.OnError(FItem, FItem.ErrorStr);
end;
FEventType := 0;
end;
{ TIpSocketPool }
procedure TIpSocketPool.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited Notify(Ptr, Action);
if Action = lnDeleted then
TIpSocketItem(Ptr).Free();
end;
procedure TIpSocketPool.BeforeDestruction();
begin
if Assigned(FIpReadThread) then
FreeAndNil(FIpReadThread);
if Assigned(FLock) then
FreeAndNil(FLock);
inherited BeforeDestruction;
end;
function TIpSocketPool.DataPortOpen(ADataPortIP: TDataPortIP;
AIncomingMsgHandler: TMsgEvent; AErrorHandler: TMsgEvent;
AConnectHandler: TNotifyEvent): TIpSocketItem;
var
i: Integer;
begin
for i := 0 to Count-1 do
begin
Result := GetItem(i);
if Result.DataPortIP = ADataPortIP then
Exit;
end;
Result := TIpSocketItem.Create();
Result.DataPortIP := ADataPortIP;
Result.OnIncomingMsg := AIncomingMsgHandler;
Result.OnError := AErrorHandler;
Result.OnConnect := AConnectHandler;
Result.Active := True;
if not Assigned(FLock) then
FLock := TCriticalSection.Create();
FLock.Acquire();
try
Add(Result);
finally
FLock.Release();
end;
if (not Assigned(FIpReadThread)) then
begin
// create socket reader
FIpReadThread := TIpReadThread.Create(True);
(FIpReadThread as TIpReadThread).IpSocketPool := Self;
FIpReadThread.Suspended := False;
end;
end;
procedure TIpSocketPool.DataPortClose(ADataPortIP: TDataPortIP);
var
i, ActiveCount: Integer;
Item: TIpSocketItem;
begin
ActiveCount := 0;
if Assigned(FLock) then
begin
FLock.Acquire();
try
for i := Count-1 downto 0 do
begin
Item := GetItem(i);
if Item.DataPortIP = ADataPortIP then
begin
Item.DataPortIP := nil;
Item.OnIncomingMsg := nil;
Item.OnError := nil;
Item.OnConnect := nil;
Break;
end
else if Assigned(Item.DataPortIP) then
Inc(ActiveCount);
end;
finally
FLock.Release();
end;
end;
{if (ActiveCount = 0) then
begin
if Assigned(FIpReadThread) then
FreeAndNil(FIpReadThread);
if Assigned(FLock) then
FreeAndNil(FLock);
end; }
end;
function TIpSocketPool.GetItem(AIndex: Integer): TIpSocketItem;
begin
Result := TIpSocketItem(Get(AIndex));
end;
{ TIpSocketItem }
function TIpSocketItem.GetLocalHost(): string;
begin
if Assigned(Socket) then
begin
Socket.GetSinLocal();
Result := Socket.GetLocalSinIP;
end
else
Result := '';
end;
function TIpSocketItem.GetLocalPort(): string;
begin
if Assigned(Socket) then
begin
Socket.GetSinLocal();
Result := IntToStr(Socket.GetLocalSinPort);
end
else
Result := '';
end;
function TIpSocketItem.SendString(const ADataStr: AnsiString): Boolean;
var
LockTryCount: Integer;
begin
//TxDataStr := TxDataStr + ADataStr;
Result := False;
if Assigned(Socket) then
begin
// try to acquire exclusive lock
LockTryCount := 10;
while (InterLockedIncrement(LockCount) > 1) and (LockTryCount > 0) do
begin
InterLockedDecrement(LockCount);
Dec(LockTryCount);
if (LockTryCount = 0) then
Exit;
Sleep(1);
end;
try
try
Result := Socket.CanWrite(0);
if Result then
begin
Socket.SendString(ADataStr);
Result := (Socket.LastError = 0);
if not Result then
begin
ErrorStr := IntToStr(Socket.LastError) + ' ' + Socket.LastErrorDesc;
end;
end;
except
ErrorStr := 'Socket write exception';
end;
finally
// release exclusive lock
InterLockedDecrement(LockCount);
end;
end;
end;
function TIpSocketItem.SendStream(st: TStream): Boolean;
begin
Result := False;
if Assigned(st) and (st.Size <> 0) and Assigned(Socket) then
begin
st.Position := 0;
try
Result := Socket.CanWrite(0);
if Result then
begin
Socket.SendStream(st);
Result := (Socket.LastError = 0);
if not Result then
begin
ErrorStr := IntToStr(Socket.LastError) + ' ' + Socket.LastErrorDesc;
end;
end;
except
ErrorStr := 'Socket write exception';
end;
end;
end;
{ TDataPortIP }
constructor TDataPortIP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
self.FLock := TMultiReadExclusiveWriteSynchronizer.Create();
Self.FRemoteHost := '';
Self.FRemotePort := '';
Self.FActive := False;
end;
procedure TDataPortIP.Open(const AInitStr: string = '');
var
n: integer;
begin
// Set host and port from init string
if AInitStr <> '' then
begin
n := Pos(':', AInitStr);
if n > 0 then
begin
Self.FRemoteHost := Copy(AInitStr, 1, n - 1);
Self.FRemotePort := Copy(AInitStr, n + 1, MaxInt);
end
else
Self.FRemoteHost := AInitStr;
end;
if Assigned(GlobalIpSocketPool) then
begin
FIpSocketItem := GlobalIpSocketPool.DataPortOpen(Self, OnIncomingMsgHandler, OnErrorHandler, OnConnectHandler);
end;
// don't inherits Open() - OnOpen event will be after successfull connection
end;
procedure TDataPortIP.Close();
begin
FIpSocketItem := nil;
if Active and Assigned(GlobalIpSocketPool) then
GlobalIpSocketPool.DataPortClose(Self);
inherited Close();
end;
destructor TDataPortIP.Destroy();
begin
FIpSocketItem := nil;
if Assigned(GlobalIpSocketPool) then
GlobalIpSocketPool.DataPortClose(Self);
FreeAndNil(FLock);
inherited Destroy();
end;
procedure TDataPortIP.OnConnectHandler(Sender: TObject);
begin
FActive := True;
if Assigned(OnOpen) then
OnOpen(Self);
end;
procedure TDataPortIP.SetIpProtocol(AValue: TIpProtocolEnum);
begin
if FIpProtocol = AValue then Exit;
Close();
FIpProtocol := AValue;
end;
function TDataPortIP.GetLocalHost: string;
begin
if Assigned(FIpSocketItem) then
Result := FIpSocketItem.GetLocalHost()
else
Result := '';
end;
function TDataPortIP.GetLocalPort: string;
begin
if Assigned(FIpSocketItem) then
Result := FIpSocketItem.GetLocalPort()
else
Result := '';
end;
procedure TDataPortIP.OnIncomingMsgHandler(Sender: TObject; const AMsg: string);
begin
if AMsg <> '' then
begin
if Assigned(FOnDataAppear) then
FOnDataAppear(self);
end;
end;
procedure TDataPortIP.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
FIpSocketItem := nil;
if Assigned(Self.FOnError) then
Self.FOnError(Self, AMsg);
FActive := False;
end;
function TDataPortIP.Peek(ASize: Integer): AnsiString;
begin
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Copy(FIpSocketItem.RxDataStr, 1, ASize);
finally
FLock.EndRead();
end;
end;
end;
function TDataPortIP.PeekSize(): Cardinal;
begin
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Cardinal(Length(FIpSocketItem.RxDataStr));
finally
FLock.EndRead();
end;
end
else
Result := 0;
end;
function TDataPortIP.Pull(ASize: Integer): AnsiString;
begin
Result := '';
if Assigned(FIpSocketItem) then
begin
FLock.BeginRead();
try
Result := Copy(FIpSocketItem.RxDataStr, 1, ASize);
Delete(FIpSocketItem.RxDataStr, 1, ASize);
finally
FLock.EndRead();
end;
end;
end;
function TDataPortIP.Push(const AData: AnsiString): boolean;
begin
Result := False;
if Assigned(FIpSocketItem) and FLock.BeginWrite() then
begin
try
Result := FIpSocketItem.SendString(AData);
finally
FLock.EndWrite();
end;
end;
end;
procedure TDataPortTCP.Open(const AInitStr: string = '');
begin
FIpProtocol := ippTCP;
inherited Open(AInitStr);
FActive := True;
end;
procedure TDataPortUDP.Open(const AInitStr: string = '');
begin
FIpProtocol := ippUDP;
inherited Open(AInitStr);
FActive := True;
end;
function TDataPortUDP.PushTo(const AData: AnsiString; ADestAddr: string
): Boolean;
var
n: integer;
ss, sh, sp: string;
begin
Result := False;
if Assigned(FIpSocketItem) and Assigned(FIpSocketItem.Socket) then
begin
if ADestAddr = '' then
begin
//UdpSocket.SetRemoteSin(remoteHost, remotePort);
end
else
begin
ss := ADestAddr;
n := Pos(':', ss);
sh := Copy(ss, 1, n - 1);
sp := Copy(ss, n + 1, MaxInt);
FIpSocketItem.Socket.SetRemoteSin(sh, sp);
end;
FIpSocketItem.Socket.SendString(AData);
Result := (FIpSocketItem.Socket.LastError = 0);
if not Result then
begin
FIpSocketItem.ErrorStr := IntToStr(FIpSocketItem.Socket.LastError) + ' ' + FIpSocketItem.Socket.LastErrorDesc;
end;
end;
end;
initialization
GlobalIpSocketPool := TIpSocketPool.Create();
finalization
FreeAndNil(GlobalIpSocketPool);
end.