c#socket connect&接收数据

时间:2015-12-15 05:40:32

标签: c# sockets tcp-ip

我有一个连接到套接字的函数:

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);
        }
    }
}

正在接收数据的功能:

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);
                }
            }
        }

在极少数情况下,当我的互联网滞后或无论如何不稳定时,我陷入了OnReceiveData功能。 Socket连接并保持连接,但我没有得到服务器的任何响应,因此OnReceiveData函数调用它自己并陷入循环。

有没有办法在接收数据部分时添加timeout或任何其他检查?

1 个答案:

答案 0 :(得分:0)

您是否尝试使用类似AsyncWaitHandle.WaitOne();的内容,请查看以下解决方案

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