如何防止套接字或连接关闭?

本文关键字:连接 何防止 套接字 | 更新日期: 2023-09-27 18:18:55

我使用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(即什么都不做)命令,只是为了防止它超时。这样的数据包被称为"心跳"或"保持存活"信号,并且应该比实际超时更频繁地发送,以防丢失或延迟到达。这最好通过启动一个辅助线程来完成,当连接被标记为打开时,该线程除了发送心跳之外什么都不做。