从客户端取消服务器套接字

时间:2018-04-24 16:30:29

标签: c# .net sockets

通过.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());
    }
} 

0 个答案:

没有答案