首页 > 解决方案 > 从客户端取消服务器套接字

问题描述

通过 .NET 异步套接字进行大型慢速馈送。数据来自仪器,因此可以是每秒 1 行(或更多)。有时它可能会停滞不前。

使用 MSDN 中的两个示例
asynchronous-client-socket-example
asynchronous-server-socket-example

我有来自套接字客户端的要求,停止从服务器中间流传输。每条消息都很小。不需要停止中间消息。需要能够停止循环 - 可以接收 1000 条小消息(发送给客户端)。

我的想法是保存引用client并调用:

client.Shutdown(SocketShutdown.Both);
client.Close();

这是正确的方法吗?

private static Socket client;
private static void StartClient()
{
    // Connect to a remote device.  
    try
    {
        // Establish the remote endpoint for the socket.  
        // The name of the   
        // remote device is "host.contoso.com".  
        //IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com"); Dns.GetHostName()
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

        // Create a TCP/IP socket.  
        Socket client = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);
        //client = new Socket(ipAddress.AddressFamily,
        //    SocketType.Stream, ProtocolType.Tcp);

        // Connect to the remote endpoint.  
        client.BeginConnect(remoteEP,
                            new AsyncCallback(ConnectCallback), client);
        connectDone.WaitOne();

        // Send test data to the remote device.  
        Send(client, "This is a test<EOF>");
        sendDone.WaitOne();

        // Receive the response from the remote device.  
        Receive(client);
        receiveDone.WaitOne();

        // Write the response to the console.  
        Console.WriteLine("Response received : {0}", response);

        // Release the socket.  
        client.Shutdown(SocketShutdown.Both);
        client.Close();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
} 

标签: c#.netsockets

解决方案


推荐阅读