简体   繁体   中英

c# socket connect & receive data

I have a function that connects to a socket:

public void Connect(string ip, ushort port)
{
    try
    {
        m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        m_recv_buffer = new TransferBuffer(8192, 0, 0);
        m_localSecurity = new Session(UsageMode.Client);

        IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(ip), port);
        m_clientSocket.Connect(localEP);

        m_clientSocket.BeginReceive(m_recv_buffer.Buffer, 0, m_recv_buffer.Buffer.Length, SocketFlags.None, OnReceiveData, m_clientSocket);

    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
        {
            Debugger(string.Format("[ClientConnect] Socket Exception: {0}", ex.InnerException.Message), System.Drawing.Color.Gray);
        }
        else
        {
            Debugger(string.Format("[ClientConnect] Socket Exception: {0}", ex), System.Drawing.Color.Gray);
        }
    }
}

And function that is receiving data:

private void OnReceiveData(IAsyncResult ar)
        {
            Socket asyncState = (Socket)ar.AsyncState;

            if (asyncState.Connected)
            {
                try
                {
                    int readCount = asyncState.EndReceive(ar);
                    if (readCount > 0)
                    {
                        m_recv_buffer.Offset = 0;
                        m_recv_buffer.Size = readCount;
                        TransferBuffer buf = new TransferBuffer(m_recv_buffer.Buffer, 0, readCount, false);
                        m_localSecurity.Recv(buf);
                        Array.Clear(m_recv_buffer.Buffer, 0, m_recv_buffer.Buffer.Length);
                    }

                    asyncState.BeginReceive(m_recv_buffer.Buffer, 0, m_recv_buffer.Buffer.Length, SocketFlags.None, OnReceiveData, asyncState);
                }
                catch (SocketException sex)
                {
                    Debugger(string.Format("[OnReceiveData] Socket Exception: {0}", sex),System.Drawing.Color.Gray);
                }
                catch (Exception ex)
                {
                    Debugger(string.Format("[OnReceiveData] Exception: {0}", ex), System.Drawing.Color.Gray);
                }
            }
        }

On some rare occasions when my internet is lagging or is in anyway unstable i am stuck in a OnReceiveData function. Socket connects and stays connected but I do not get any response from the server so OnReceiveData function is calling it self and gets stuck in a loop.

Is there a way to add a timeout or any other check on receiving data part?

Have you tried using something like AsyncWaitHandle.WaitOne(); take a look at the following solution

Implementation-of-Connecting-a-Socket-with-Timeout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM