SOCKET client = accept(listen_sock, 0, 0);
timeval client_to;
client_to.tv_sec = 1;
client_to.tv_usec = 0;
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, (char*)&client_to, sizeof(client_to));
char buffer[1024];
while ((ret = recv(client, buffer, 1024, 0)) != 0)
{
cout << "<in loop>" << endl;
if (ret == -1 && WSAGetLastError() != WSAETIMEDOUT) break;
if (ret > 0) cout << std::string(buffer, 0, ret) << endl;
}
closesocket(client);
Above code is a part of simple echo server written in C++. The problems what I'm facing are...
- How to set timeout value and detect timeout time is expired?
- How to detect disconnection of the socket?
Please let me show some code in C#. Thanks.
added >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Part of my C# code is follow...
try
{
// Read all
spider.Client.ReceiveTimeout = 500; // spider is TcpClient type and blocking socket.
int readCount = 0;
SocketError socketError;
while ((readCount = spider.Client.Receive(tempBuffer, 0, tempBuffer.Length, SocketFlags.None, out socketError)) > 0) // I think time-out does not work, Receive() returns immediately.
{
recvBuffer.Append(tempBuffer, 0, readCount);
}
}
catch (Exception e) // even though spider is disconnect, no exception occurred. how can I detect disconnection?
{
Console.WriteLine("Exception: {0}", e.Message);
}