BlockingTCPClient.pas 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. {
  2. 文件名:BlockingTCPClient.pas
  3. 功 能:阻塞方式TCP客户端组件,单独线程接收数据。
  4. 建 立:尹进
  5. 历 史:
  6. 2005.12.23:补文件说明信息(尹进)
  7. }
  8. unit BlockingTCPClient;
  9. interface
  10. uses
  11. WinSock2, RealICQSocket, RealICQProxy,
  12. SysUtils, Classes, Windows;
  13. type
  14. {$M+}
  15. TBlockingTCPClientRecvThread = class;
  16. TBlockingTCPClientReceivedDataEvent = procedure(Sender: TObject; RecvThread: TBlockingTCPClientRecvThread; RecvBytes: Integer) of object;
  17. TBlockingTCPClientSendedDataEvent = procedure(Sender: TObject; SendBytes: Integer) of object;
  18. TBlockingTCPClientBeforeSendDataEvent = procedure(Sender: TObject; var Buf; Size: Integer) of object;
  19. TBlockingTCPClient = class
  20. private
  21. FEncryptCriticalSection: TRTLCriticalSection;
  22. FConnected: Boolean;
  23. FSocket: TSocket;
  24. FRemoteAddress: String;
  25. FRemotePort: Integer;
  26. FProxy: TProxy;
  27. FRecvBufferSize: Integer;
  28. FCallSynchronize: Boolean;
  29. FLocalAddress: String;
  30. FLocalPort: Integer;
  31. FNoDelay: Boolean;
  32. FOnConnected: TNotifyEvent;
  33. FOnDisconnected: TNotifyEvent;
  34. FOnReceivedData: TBlockingTCPClientReceivedDataEvent;
  35. FOnSendedData: TBlockingTCPClientSendedDataEvent;
  36. FOnBeforeSendData: TBlockingTCPClientBeforeSendDataEvent;
  37. procedure SetRemoteAddress(Value:String);
  38. procedure SetRemotePort(Value:Integer);
  39. procedure SetProxy(Value:TProxy);
  40. procedure SetRecvBufferSize(Value:Integer);
  41. procedure SetNoDelay(Value: Boolean);
  42. protected
  43. procedure DoConnected;
  44. procedure DoDisconnected;
  45. procedure DoReceivedData(RecvThread: TBlockingTCPClientRecvThread; RecvBytes: Integer);
  46. procedure DoSendedData(SendBytes: Integer);
  47. procedure DoBeforeSendData(var Buf; Size: Integer);
  48. public
  49. constructor Create;
  50. destructor Destroy; override;
  51. procedure Connect(StartRecvThread: Boolean = True);
  52. procedure Disconnect;
  53. procedure SendBuffer(var Buf; Size: Integer);
  54. property SocketNO: TSocket read FSocket;
  55. property NoDelay: Boolean read FNoDelay write SetNoDelay;
  56. property CallSynchronize: Boolean read FCallSynchronize write FCallSynchronize;
  57. property RemoteAddress: String read FRemoteAddress write SetRemoteAddress;
  58. property RemotePort: Integer read FRemotePort write SetRemotePort;
  59. property Proxy: TProxy read FProxy write SetProxy;
  60. property Connected: Boolean read FConnected;
  61. property RecvBufferSize: Integer read FRecvBufferSize write SetRecvBufferSize;
  62. property LocalAddress: String read FLocalAddress write FLocalAddress;
  63. property LocalPort: Integer read FLocalPort write FLocalPort;
  64. property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
  65. property OnDisconnected: TNotifyEvent read FOnDisconnected write FOnDisconnected;
  66. property OnReceivedData: TBlockingTCPClientReceivedDataEvent read FOnReceivedData write FOnReceivedData;
  67. property OnSendedData: TBlockingTCPClientSendedDataEvent read FOnSendedData write FOnSendedData;
  68. property OnBeforeSendData: TBlockingTCPClientBeforeSendDataEvent read FOnBeforeSendData write FOnBeforeSendData;
  69. end;
  70. //用于接收数据的线程
  71. TBlockingTCPClientRecvThread = class(TThread)
  72. private
  73. FBlockingTCPClient: TBlockingTCPClient;
  74. FBuf: array of Byte;
  75. FNotProcessedBufferLength: Integer;
  76. FRecvBytes: Integer;
  77. procedure DoDisconnect;
  78. procedure DoReceivedData();
  79. protected
  80. procedure Execute; override;
  81. public
  82. constructor Create(ABlockingTCPClient: TBlockingTCPClient);
  83. destructor Destroy; override;
  84. procedure CopyRecvBufferTo(var Buf; Offset: Integer; Size: Integer);
  85. procedure CutRecvBufferTo(var Buf; Offset: Integer; Size: Integer);
  86. published
  87. property NotProcessedBufferLength: Integer read FNotProcessedBufferLength;
  88. end;
  89. implementation
  90. uses
  91. LoggerImport;
  92. {TBlockingTCPClient}
  93. //------------------------------------------------------------------------------
  94. procedure TBlockingTCPClient.SetNoDelay(Value: Boolean);
  95. begin
  96. if FSocket <> INVALID_SOCKET then
  97. begin
  98. FNoDelay := Value;
  99. setsockopt(FSocket, IPPROTO_TCP, TCP_NODELAY, @FNoDelay, SizeOf(FNoDelay));
  100. end;
  101. end;
  102. //------------------------------------------------------------------------------
  103. constructor TBlockingTCPClient.Create;
  104. begin
  105. inherited Create;
  106. InitializeCriticalSection(FEncryptCriticalSection);
  107. FCallSynchronize := True;
  108. FNoDelay := False;
  109. FConnected := False;
  110. FSocket := INVALID_SOCKET;
  111. FProxy := TProxy.Create;
  112. FRecvBufferSize := 65534;
  113. // FRecvBufferSize := 8192 * 2;
  114. end;
  115. //------------------------------------------------------------------------------
  116. destructor TBlockingTCPClient.Destroy;
  117. begin
  118. try
  119. if Connected then Disconnect;
  120. FProxy.Free;
  121. finally
  122. EnterCriticalSection(FEncryptCriticalSection);
  123. DeleteCriticalSection(FEncryptCriticalSection);
  124. inherited Destroy;
  125. end;
  126. end;
  127. //------------------------------------------------------------------------------
  128. procedure TBlockingTCPClient.Connect(StartRecvThread: Boolean = True);
  129. var
  130. serverAddr: TSockAddrIn;
  131. BindProxyAddr: TSockAddrIn;
  132. lastError: Integer;
  133. ARemoteIP: String;
  134. ret:Integer;
  135. LocalAddr: TSockAddrIn;
  136. Length: Integer;
  137. begin
  138. if FRemoteAddress = '' then raise TSocketException.Create('Server address empty');
  139. if FRemotePort = 0 then raise TSocketException.Create('Server port empty');
  140. if Connected then Disconnect;
  141. case FProxy.ProxyType of
  142. ptNone:
  143. begin
  144. FSocket := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  145. if FSocket = INVALID_SOCKET then raise TSocketException.CreateFmt('ErrorCode:%d',[WSAGetLastError]);
  146. if not HostToIP(FRemoteAddress, ARemoteIP) then ARemoteIP := FRemoteAddress;
  147. serverAddr.sin_family:= AF_INET;
  148. serverAddr.sin_port:= htons(FRemotePort);
  149. serverAddr.sin_addr.S_addr:= inet_addr(PAnsiChar(ARemoteIP));
  150. ret := WinSock2.connect(FSocket,@serverAddr,SizeOf(serverAddr));
  151. if ret = SOCKET_ERROR then begin lastError := WSAGetLastError(); if lastError <> 0 then raise TSocketException.CreateFmt('连接失败:%d',[lastError]); end;
  152. end;
  153. ptSocks5:
  154. begin
  155. if FProxy.Address = '' then raise TSocketException.Create('Proxy server address Empty');
  156. if FProxy.Port = 0 then raise TSocketException.Create('Proxy server port Empty');
  157. FSocket := ConnectToSocks5Proxy(FRemoteAddress, FRemotePort,
  158. FProxy.Address, FProxy.Port,
  159. FProxy.Username, FProxy.Password,
  160. ppTCP, BindProxyAddr);
  161. end;
  162. ptHttp:
  163. begin
  164. if FProxy.Address = '' then raise TSocketException.Create('Proxy server address Empty');
  165. if FProxy.Port = 0 then raise TSocketException.Create('Proxy server port Empty');
  166. FSocket := ConnectToHttpProxy(FRemoteAddress, FRemotePort,
  167. FProxy.Address, FProxy.Port,
  168. FProxy.Username, FProxy.Password, FProxy.Domain);
  169. end;
  170. end;
  171. Length := SizeOf(LocalAddr);
  172. getSockname(FSocket, LocalAddr, Length);
  173. FLocalAddress := inet_ntoa(LocalAddr.sin_addr);
  174. FLocalPort := ntohs(localAddr.sin_port);
  175. FConnected := True;
  176. DoConnected;
  177. if StartRecvThread then TBlockingTCPClientRecvThread.Create(Self);
  178. end;
  179. //------------------------------------------------------------------------------
  180. procedure TBlockingTCPClient.Disconnect;
  181. begin
  182. if FSocket <> INVALID_SOCKET then
  183. begin
  184. try
  185. try
  186. shutdown(FSocket, SD_BOTH);
  187. finally
  188. closeSocket(FSocket);
  189. FSocket := INVALID_SOCKET;
  190. end;
  191. finally
  192. FConnected := False;
  193. DoDisconnected;
  194. end;
  195. end;
  196. end;
  197. //------------------------------------------------------------------------------
  198. procedure TBlockingTCPClient.SendBuffer(var Buf; Size: Integer);
  199. var
  200. SendBytes,
  201. ErrorCode: Integer;
  202. begin
  203. ErrorCode := 0;
  204. try
  205. EnterCriticalSection(FEncryptCriticalSection);
  206. DoBeforeSendData(Buf, Size);
  207. SendBytes:= send(FSocket, Buf, Size, 0);
  208. if SendBytes = 0 then
  209. begin
  210. Info('SendBytes = 0:' + SysErrorMessage(ErrorCode),'TBlockingTCPClient.SendBuffer');
  211. Disconnect;
  212. Exit;
  213. end;
  214. if SendBytes = SOCKET_ERROR then
  215. begin
  216. ErrorCode := GetLastError;
  217. if (ErrorCode = WSAECONNABORTED) or
  218. (ErrorCode = WSAECONNRESET) or
  219. (ErrorCode = WSAETIMEDOUT) or
  220. (ErrorCode = WSAENOTSOCK) then
  221. begin
  222. Info('发送数据时报错:' + SysErrorMessage(ErrorCode),'TBlockingTCPClient.SendBuffer');
  223. Disconnect;
  224. end;
  225. end
  226. else
  227. begin
  228. DoSendedData(SendBytes);
  229. end;
  230. finally
  231. LeaveCriticalSection(FEncryptCriticalSection);
  232. end;
  233. end;
  234. //------------------------------------------------------------------------------
  235. procedure TBlockingTCPClient.DoConnected;
  236. begin
  237. if Assigned(FOnConnected) then FOnConnected(Self);
  238. end;
  239. //------------------------------------------------------------------------------
  240. procedure TBlockingTCPClient.DoBeforeSendData(var Buf; Size: Integer);
  241. begin
  242. if Assigned(FOnBeforeSendData) then FOnBeforeSendData(Self, Buf, Size);
  243. end;
  244. //------------------------------------------------------------------------------
  245. procedure TBlockingTCPClient.DoSendedData(SendBytes: Integer);
  246. begin
  247. if Assigned(FOnSendedData) then FOnSendedData(Self, SendBytes);
  248. end;
  249. //------------------------------------------------------------------------------
  250. procedure TBlockingTCPClient.DoReceivedData(RecvThread: TBlockingTCPClientRecvThread; RecvBytes: Integer);
  251. begin
  252. if Assigned(FOnReceivedData) then FOnReceivedData(Self, RecvThread, RecvBytes);
  253. end;
  254. //------------------------------------------------------------------------------
  255. procedure TBlockingTCPClient.DoDisconnected;
  256. begin
  257. if Assigned(FOnDisconnected) then FOnDisconnected(Self);
  258. end;
  259. //------------------------------------------------------------------------------
  260. procedure TBlockingTCPClient.SetRemoteAddress(Value: String);
  261. begin
  262. FRemoteAddress := Value;
  263. end;
  264. //------------------------------------------------------------------------------
  265. procedure TBlockingTCPClient.SetRemotePort(Value: Integer);
  266. begin
  267. if (Value<0) or (Value>65535) then raise TSocketException.Create('端口号必须为0-65535之间的数值');
  268. FRemotePort := Value;
  269. end;
  270. //------------------------------------------------------------------------------
  271. procedure TBlockingTCPClient.SetProxy(Value: TProxy);
  272. begin
  273. if Assigned(Value) then FProxy.Assign(Value);
  274. end;
  275. //------------------------------------------------------------------------------
  276. procedure TBlockingTCPClient.SetRecvBufferSize(Value: Integer);
  277. begin
  278. if (Value<1) or (Value>65535) then raise TSocketException.Create('缓冲区大小必须为1-65535之间的数值');
  279. if Connected then raise TSocketException.Create('连接已建立时不允许更改缓冲大小');
  280. FRecvBufferSize := Value;
  281. end;
  282. {TBlockingTCPClientRecvThread}
  283. //------------------------------------------------------------------------------
  284. procedure TBlockingTCPClientRecvThread.Execute;
  285. var
  286. ErrorCode: Integer;
  287. begin
  288. ErrorCode := 0;
  289. FreeOnTerminate := True;
  290. while (not Terminated) do
  291. begin
  292. FRecvBytes := recv(FBlockingTCPClient.FSocket, FBuf[FNotProcessedBufferLength], Length(FBuf)-FNotProcessedBufferLength, 0);
  293. if FRecvBytes = SOCKET_ERROR then
  294. begin
  295. ErrorCode := GetLastError;
  296. if (ErrorCode = WSAECONNABORTED) or
  297. (ErrorCode = WSAECONNRESET) or
  298. (ErrorCode = WSAETIMEDOUT) or
  299. (ErrorCode = WSAENOTSOCK) then
  300. begin
  301. try
  302. Error('接收数据时报错:' + SysErrorMessage(ErrorCode) + ' ' +FBlockingTCPClient.FRemoteAddress + ':' + IntToStr(FBlockingTCPClient.FRemotePort),'TBlockingTCPClientRecvThread.Execute');
  303. Synchronize(DoDisconnect);
  304. except
  305. end;
  306. Exit;
  307. end
  308. else
  309. begin
  310. Sleep(1);
  311. Continue;
  312. end;
  313. end;
  314. if FRecvBytes = 0 then
  315. begin
  316. try
  317. Error('RecvBytes = 0' + SysErrorMessage(ErrorCode),'recv');
  318. Synchronize(DoDisconnect);
  319. except
  320. end;
  321. Exit;
  322. end
  323. else
  324. begin
  325. FNotProcessedBufferLength := FNotProcessedBufferLength + FRecvBytes;
  326. try
  327. if FBlockingTCPClient.FCallSynchronize then
  328. Synchronize(DoReceivedData)
  329. else
  330. DoReceivedData;
  331. except
  332. end;
  333. end;
  334. end;
  335. end;
  336. //------------------------------------------------------------------------------
  337. procedure TBlockingTCPClientRecvThread.DoReceivedData();
  338. begin
  339. if Assigned(FBlockingTCPClient) then FBlockingTCPClient.DoReceivedData(Self, FRecvBytes);
  340. end;
  341. //------------------------------------------------------------------------------
  342. procedure TBlockingTCPClientRecvThread.DoDisconnect;
  343. begin
  344. // Info('断开:' + SysErrorMessage(GetLastError),'DoDisconnect');
  345. if Assigned(FBlockingTCPClient) then FBlockingTCPClient.Disconnect;
  346. end;
  347. //------------------------------------------------------------------------------
  348. procedure TBlockingTCPClientRecvThread.CopyRecvBufferTo(var Buf; Offset: Integer; Size: Integer);
  349. begin
  350. CopyMemory(@Buf,@FBuf[Offset],Size);
  351. end;
  352. //------------------------------------------------------------------------------
  353. procedure TBlockingTCPClientRecvThread.CutRecvBufferTo(var Buf; Offset: Integer; Size: Integer);
  354. begin
  355. CopyMemory(@Buf, @FBuf[Offset], Size);
  356. CopyMemory(FBuf, @FBuf[Offset+Size], Length(FBuf)-(Offset+Size));
  357. FNotProcessedBufferLength := FNotProcessedBufferLength - (Offset+Size);
  358. end;
  359. //------------------------------------------------------------------------------
  360. constructor TBlockingTCPClientRecvThread.Create(ABlockingTCPClient: TBlockingTCPClient);
  361. begin
  362. inherited Create(True);
  363. FBlockingTCPClient := ABlockingTCPClient;
  364. SetLength(FBuf,FBlockingTCPClient.RecvBufferSize);
  365. FNotProcessedBufferLength := 0;
  366. Resume;
  367. end;
  368. //------------------------------------------------------------------------------
  369. destructor TBlockingTCPClientRecvThread.Destroy;
  370. begin
  371. inherited Destroy;
  372. end;
  373. end.