我想将简单的C ++ echo服务器移植到C#

时间:2009-06-18 03:41:38

标签: c# c++ networking sockets

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服务器的一部分。 我面临的问题是......

  1. 如何设置超时值并检测超时时间已过期?
  2. 如何检测插座断开?
  3. 请让我在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);
    
    }
    

1 个答案:

答案 0 :(得分:0)

通过 XF.Server 查看。strong的 kodart 套接字库。下载库时,它附带一个echo服务器作为Xf.Server库的示例实现。这对你有用。

www.kodart.com

感谢。