gpt4 book ai didi

sockets - TServerSocket : How check if a specific client on ListView still is connected before send message?

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

我有一个 Timer并希望向 ListView 的每个客户端发送一条消息例如,确定 ping 时间。然后我有以下代码:

procedure TMainForm.Timer1Timer(Sender: TObject);
var
i: Integer;
begin
try
for i := 0 to ListView1.Items.count - 1 do
begin
ListView1.Items.Item[i].SubItems.Objects[2] := TObject(GetTickCount);
ServerSocket1.Socket.Connections[i].SendText('ping' + #13#10);
end;
except
exit;
end;
end;

在发送之前,可能更适合检查客户端是否真的连接或类似的。这个怎么做?提前致谢。

最佳答案

无需检查连接。如果客户端实际断开连接,它不会在服务器的Connections[] 中。当您的 OnTimer 时不再列出处理程序被触发。你应该有一个 OnClientDisconnect分配给 TServerSocket 的处理程序从 TListView 中删除客户端.

如果由于某种原因,客户端仍在 Connections[]列表(即,因为底层连接已丢失但 TServerSocket 尚未检测到它),然后套接字将简单地缓存所有传出数据,直到其出站缓冲区填满,然后它将开始返回 WSAWOULDBLOCK每次发送的错误。最终,操作系统将超时死连接和TServerSocket将从 Connections[] 中删除它列表,触发 OnClientDisconnect事件。

至少,在您显示的代码中,您应该将发送循环更新为 Close()任何实际发送失败的套接字,从而触发 OnClientDisconnectTListView 中删除该客户端的事件,例如:

procedure TMainForm.ServerSocket1ClientConnect(Sender: TObject; Socket: TCustomWinSocket);
var
Item: TListItem;
begin
Item := ListView1.Items.Add;
Item.Data := Socket;
...
end;

procedure TMainForm.ServerSocket1ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket);
var
Item: TListItem;
begin
Item := ListView1.FindData(0, Socket, True, False);
if Item <> nil then
Item.Delete;
end;

procedure TMainForm.Timer1Timer(Sender: TObject);
const
s: AnsiString = 'ping' + #13#10;
var
Item: TListItem;
Socket: TCustomWinSocket;
p: PAnsiChar;
i, len, sent: Integer;
begin
for i := 0 to ListView1.Items.Count - 1 do
begin
Item := ListView1.Items[i];
Item.SubItems.Objects[2] := TObject(GetTickCount);
Socket := TCustomWinSocket(Item.Data);
try
// SendText() does not handle partial sends, or Unicode strings...
//Socket.SendText('ping' + #13#10);
p := PAnsiChar(s);
len := Length(s);
repeat
sent := Socket.SendBuf(p^, len);
if sent = -1 then
being
if WSAGetLastError() <> WSAEWOULDBLOCK then
Break;
// TODO: stop trying after several attempts fail...
Continue;
end;
Inc(p, sent);
Dec(len, sent);
until len = 0;
if len = 0 then
Continue;
except
end;
Socket.Close;
end;
end;

关于sockets - TServerSocket : How check if a specific client on ListView still is connected before send message?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176790/

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