Search code examples
c#socketscompact-framework

How to create C# Compact Framework non-blocking sockets


I am trying to create a non-blocking socket in WM6 C# but I keep getting the following compiler error:

"Synchronous calls are not supported on non-blocking sockets. Set Blocking=true or use the asynchronous methods."

However when I use the BeginReceive() asynchronous methods, the EndReceive() is blocked. Same for BeginSend() and EndSend(). How do you do a non-blocking socket within the compact framework?

Here's my code. I am not using an AsyncCallback method because I want to return the bytesRecv and bytesSent variables.

    private void asyncReceive(byte[] recvBytes, int offset, int size, SocketFlags sf)
    {
        IAsyncResult asyncResult = null;
        int recvBytes = 0;

        try
        {
            asyncResult = _socket.BeginSend(sendBytes, offset, size, sf, null, null);
            recvBytes = _socket.EndSend(asyncResult);  // <-- This blocks even with _socket.Blocking = false;
        }
        catch (SocketException)
        {
            //Check SocketException.ErrorCode...
        }

        return recvBytes;
    }  

Solution

  • Looks like you're missing the point- the behavior you're seeing is by design. I'd suggest reading up on async programming in .NET (lots of resources- maybe start here). Non-blocking socket reads/writes with BeginXXX will allow you to start the send/receive, then go do something else and be notified by the kernel when it's done (via the AsyncCallback), at which point you'd call the corresponding EndXXX method to get the result. If you call EndXXX right after the BeginXXX call before the operation is complete, it's designed to block until completion.

    To get non-blocking behavior, you'll need to break up your code a bit to handle the callback correctly (eg, marshal the result back to your UI, whatever). You won't have the answer as to how many bytes were sent/received until that's actually been done by the underlying kernel bits.