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);
上面的代码是用C ++编写的简单echo服务器的一部分。 我面临的问题是......
请让我在C#中显示一些代码。感谢。
添加&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;
我的部分C#代码遵循......
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);
}