C#如何防止插座或连接关闭?

C#如何防止插座或连接关闭?,c#,C#,我正在使用C#编写的应用程序,通过IP连接到我们的一些设备。应用程序与设备连接良好,我们可以发送配置所需的命令。我遇到的问题是,在断开连接后,在大约40秒到一分钟内没有发送任何命令。我想知道我能做些什么使插座保持至少几分钟的活动状态。需要一些关于实施心跳的指导,任何帮助都将不胜感激 下面是我们正在使用的代码 using System; using System.Net; using System.Net.Sockets; using System.Threading; u

我正在使用C#编写的应用程序,通过IP连接到我们的一些设备。应用程序与设备连接良好,我们可以发送配置所需的命令。我遇到的问题是,在断开连接后,在大约40秒到一分钟内没有发送任何命令。我想知道我能做些什么使插座保持至少几分钟的活动状态。需要一些关于实施心跳的指导,任何帮助都将不胜感激

下面是我们正在使用的代码

using System;
using System.Net;    
using System.Net.Sockets;    
using System.Threading;    
using System.Text;    
using System.Globalization;    

// State object for receiving data from remote device.    
public class StateObject
{

    // Client socket.
    public Socket workSocket = null;

    // Size of receive buffer.
    public const int BufferSize = 256;

    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];

    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{

    // The port number for the remote device.
    //private const int port = 1000;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    static Socket client;

    internal static Boolean StartClient(string ip_address, int port)
    {
        // Connect to a remote device.
        Boolean bRtnValue = false;
        try
        {

            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            //IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
            IPAddress ipAddress = IPAddress.Parse(ip_address);
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork,
                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.
            string msg = ((char)2) + "S" + (char)13;
            Send(client, msg);
            //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);
            bRtnValue = true;

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

        //return value 
        return bRtnValue;
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {

                // There might be more data, so store the data received so far.
                state.sb.Clear();
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + state.sb.ToString());
                //54A111503000000000017D8857E3
                //IDSSSSSSSSSSSSSSSSTTTTCCCCKK    017D
                if (state.sb.ToString(0, 2) == "54")
                {
                    string hexString = state.sb.ToString(18, 4);
                    int num = Int32.Parse(hexString, NumberStyles.HexNumber);
                    double degreesF = ((double)num / 16.0) * 9.0 / 5.0 + 32.0;
                    string f = degreesF.ToString("#.#");
                    Console.WriteLine(" " + f);
                }

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                Console.WriteLine("data");
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Send(Socket client, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    internal void StartListening(string ip_address, int port)
    {
        StartClient(ip_address, port);
    }

其原因是所谓的超时,据我所知,当连接的另一端中止、断开连接或以其他方式完全停止传输数据时,每个网络协议都要处理的一个重要特性。毕竟,没有办法发送一个数据包,上面写着“我的猫刚刚把我的路由器撞坏了,中断了连接。”


您需要做的是,如评论中所述,通过网络定期发送no op(即不执行任何操作)命令,以防止超时。这类数据包被称为“心跳”或“保持激活”信号,发送频率应远高于实际超时,以防丢失或延迟到达。这最好通过启动一个辅助线程来实现,该线程在连接标记为打开时只发送心跳。

您需要实现一个计时器,在没有数据要发送时模拟心跳,即在发送最后一个数据包后,启动一个计时器几秒钟。如果在取消之前有数据要发送,请发送数据并重新启动计时器。如果计时器超时,您将发送一个虚拟数据包,并在相同的超时时间后重新启动计时器。如果设备支持,您不能定期发送任何类似ping(无操作)的命令以保持连接吗?或者,查看套接字保持活动选项。在任何情况下,这都不包括连接重置或网络关闭的情况,此时您必须重新连接。代码??????听起来您连接的服务器正在断开连接。。。在不了解其行为规则的情况下,很难告诉您任何事情,但是如果它在一定的空闲时间后断开连接,则会发送Ping消息……仅供参考:像这样的工具值得学习。它可以非常方便地确定谁决定终止连接,等等。