简体   繁体   中英

Asynchronous TCP socket not working in C#

I keep getting this error:

"The IAsyncResult object was not returned from the corresponding asynchonous method on this class. Parameter name : aysncResult. Line 105.

This happens when I attempt to connect to a local server; It errors and won't connect.

Here's my client code:

public class Client
{

    public delegate void OnConnectEventHandler(Client sender, bool connected);
    public event OnConnectEventHandler OnConnect;

    public delegate void OnSendEventHandler(Client sender, int sent);
    public event OnSendEventHandler OnSend;

    public delegate void OnDisconnectEventHandler(Client sender);
    public event OnDisconnectEventHandler OnDisconnect;

    Socket socket;

    public bool Connected
    {
        get
        {
            if (socket != null)
            {
                return socket.Connected;
            }

            return false;
        }
    }

    public Client()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }

    public void SendData()
    {

    }

    public void Connect(string IP, int port)
    {
        if (socket == null)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        socket.BeginConnect(IP, port, new AsyncCallback(sendCallback), null);


    }

    private void connectCallback(IAsyncResult ar)
    {
        //try
        //{
            socket.EndConnect(ar);

            if (OnConnect != null)
            {
                OnConnect(this, Connected);
            }
        //}
        //catch
        //{

        //}
    }

    public void Send(byte[] data, int index, int length)
    {
        socket.BeginSend(BitConverter.GetBytes(length), 0, 4, SocketFlags.None, new AsyncCallback(sendCallback), null);
        socket.BeginSend(data, index, length, SocketFlags.None, new AsyncCallback(sendCallback), null);
    }

    private void sendCallback(IAsyncResult ar)
    {
        try
        {
            int sent = socket.EndSend(ar); ( errrors here )

            if (OnSend != null)
            {
                OnSend(this, sent);
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
            return;
        }
    }

    public void Disconnect()
    {
        try
        {
            if (socket.Connected)
            {
                socket.Close();
                socket = null;
                if (OnDisconnect != null)
                {
                    OnDisconnect(this);
                }
            }
        }
        catch
        {

        }
    }

you should not have two pending BeginSend operations.

Send the size and then the buffer when it completes:

public void Send(byte[] data, int index, int length)
{
    //add data as state
    socket.BeginSend(BitConverter.GetBytes(length), 0, 4, SocketFlags.None, sendCallback, data);
}

private void sendCallback(IAsyncResult ar)
{
    try
    {
        int sent = socket.EndSend(ar); ( errrors here )

        // check if data was attached.
        if (ar.AsyncState != null)
        {
            byte[] buffer = (byte[])ar.AsyncState;
            socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, sendCallback, null);
            return;
        }

        if (OnSend != null)
        {
            OnSend(this, sent);
        }
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.ToString());
        return;
    }
}

You can also use the BeginSend overload which takes a list of buffers.

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