Delphi + Synapse: How to check if I am still connected

空扰寡人 提交于 2019-12-06 01:09:54

问题


I am using TTCPBlockSocket for a TCP/IP Application . The problem is that I can't determine when the connection is lost.

GetLastError returns 0
Read returns 0

But I encounter these values eaven if the application is connected so I can get it how can I be notified when the TCP/IP connection is lost.

Thanks


回答1:


I would say, you can use the CanRead method, passing 0 to its Timeout parameter. This function internally performs select function for the socket and returns False when an error occurs. It should be enough to use just this method since the select function returns SOCKET_ERROR if you lose the connection, and it causes the CanRead method return False as a result. So I think, it's enough to check if the socket connection is alive this way:

function IsSocketAlive(ASocket: TTCPBlockSocket): Boolean;
begin
  Result := ASocket.CanRead(0);
end;



回答2:


As opC0de says, to check if the client is still connected you need to both check TCPBlockSocket.CanRead(0) and TCPBlockSocket.WaitingData = 0

function IsSocketAlive(ASocket: TTCPBlockSocket): Boolean;
begin
  Result := (ASocket.Socket = INVALID_SOCKET) or ((ASocket.WaitingData = 0) and ASocket.CanRead(0));
end;

I'm using this way in my projects so I can confirm that it works.



来源:https://stackoverflow.com/questions/13045943/delphi-synapse-how-to-check-if-i-am-still-connected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!