gpt4 book ai didi

multithreading - TClientSocket和线程

转载 作者:行者123 更新时间:2023-12-03 18:42:18 25 4
gpt4 key购买 nike

好的,伙计们,我正在使用TClientSocket类和线程与主机列表同时工作。一切都很好,但我开始注意到一段时间后,所有线程都陷入了ReceiveBuf调用中……如果我打开10个线程,例如检查100台主机,它将启动良好,但是一段时间后,所有线程都将陷入困境,因为由于某些原因,某些主机对此ReceiveBuf调用的回答不正确...我试图执行ReceiveLength并检查receive> 0以调用ReceiveBuf,但仍无法正常工作。
我将在下面发布原始代码:

function Threads.ReceiveProtocolVersion;
var
ProtocolVersion: array[0..11] of AnsiChar;
begin
try
MySocket.Socket.ReceiveBuf(ProtocolVersion, SizeOf(ProtocolVersion));
Version:= AnsiString(ProtocolVersion);
...//continues but doesn't matter because many threads get stucked in the ReceiveBuf call...
except
Terminate; //we terminate thread if raise some exception..

好的,所以经过一些研究,我开始尝试这样做:
function Threads.ReceiveProtocolVersion;
var
ProtocolVersion: array[0..11] of AnsiChar;
SizeBuf: integer;
begin
try
SizeBuf:= MySocket.Socket.ReceiveLength;
if SizeBuf > 0 then
begin
MySocket.Socket.ReceiveBuf(ProtocolVersion, SizeOf(ProtocolVersion));
Version:= AnsiString(ProtocolVersion);
....
end;
except
Terminate; //we terminate thread if raise some exception..

显然,它解决了线程卡在ReceiveBuf调用中的问题,但是由于某些未知的原因,没有一个线程(甚至不是工作正常的线程)都进入“if SizeBuf> 0”内部。
有什么帮助吗?

//编辑显示更多的线程代码::
Thread.Execute是这样的:
procedure MyThread.Execute;
begin
while not(Terminated) do
begin
if SocketConnect then
begin
if ReceiveProtocolVersion then
begin
DoAuthentication;
end;
end;
MySocket.Close;
MySocket.Free;
end;
Terminate;
end;

SocketConnect函数为:
function MyThread.SocketConnect: bool;
begin
Result:= false;
MySocket:= TClientSocket.Create(Nil);
MySocket.Port:= StrToInt(Form1.Edit1.Text);
MySocket.ClientType:= ctBlocking;
MySocket.Host:= Host; //Host is a private variable for thread class
try
MySocket.Active:= true;
if (MySocket.Socket.Connected = true) then
Result:= true;
except
Terminate;
end;
end;

最佳答案

我使用TWinSocketStream解决了该问题。像这样的东西:

function MyThread.CheckProtocol: bool;
var
SockStream: TWinSocketStream;
ProtocolVersion: array[0..11] of AnsiChar;
begin
try
SockStream := TWinSocketStream.Create(MySocket.Socket, 3000);
SockStream.Read(ProtocolVersion, SizeOf(ProtocolVersion));
RFBVer:= AnsiString(ProtocolVersion);
....
我读到使用阻塞模式套接字的正确方法是通过以下方式通过TWinSocketStream发送/接收数据:
DocWiki Embarcadero
无论如何,感谢尝试提供帮助的家伙!

关于multithreading - TClientSocket和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16657649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com