Andi Wijaya
Andi Wijaya

Reputation: 81

C# ReceiveAsync Error

Im currently developing an appserver. I would like to use AcceptAsync method. I got error "Object reference not set to instance of object." when calling ReceiveAsync method. If there any come up with this problem and got the solution to it?

public class AppServer
{
    public void Start()
    {
        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12345));
        serverSocket.Listen(100);

        SocketAsyncEventArgs e = new SocketAsyncEventArgs();
        e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed);

        bool raiseEvent = serverSocket.AcceptAsync(e);
        if (!raiseEvent)
            AcceptCallback(e);
    }

    void e_Completed(object sender, SocketAsyncEventArgs e)
    {
        AcceptCallback(e);
    }

    private void AcceptCallback(SocketAsyncEventArgs e)
    {
        SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs();
        readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(readEventArgs_Completed);

        Socket clientSocket = e.AcceptSocket;
        bool raiseEvent = clientSocket.ReceiveAsync(readEventArgs); // <-- Error goes here
        if (!raiseEvent)
            ReceiveCallback(readEventArgs);
    }

    void readEventArgs_Completed(object sender, SocketAsyncEventArgs e)
    {
        ReceiveCallback(e);
    }

    private void ReceiveCallback(SocketAsyncEventArgs e)
    {

    }
}

Upvotes: 6

Views: 2787

Answers (2)

user627283
user627283

Reputation: 553

I had the same problem and I managed to figure it out. You need to provide to your SocketAsyncEventArgs object a data buffer (byte array) to store the data received before calling ReceiveAsync(e).

void e_Completed(object sender, SocketAsyncEventArgs e)
{
    byte[] buffer = new byte[1024];
    e.SetBuffer(buffer, 0, buffer.Length);
    AcceptCallback(e);
}

Upvotes: 7

nirmus
nirmus

Reputation: 5093

I'm not sure why you in two place accept socket. If you remove

 AcceptCallback(e);

from e_Completed everything is working.

It's link to example asynchronous server:

a link

Upvotes: -1

Related Questions