Asynchronous UDP receiving null bytes

2019-08-03 01:47发布

问题:

I have a server like this:

    public void Run() {
        while (true) {
            if (curThreads < maxThreads) {
                curThreads++;
                AsyncCallback callback = new AsyncCallback (ProcessRequest);
                client.BeginReceive (callback, this);
            }
        }
    }

And the callback is:

    public static void ProcessRequest(IAsyncResult result) {
        LogSink lg = result.AsyncState as LogSink;

        IPEndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
        byte[] message = lg.client.EndReceive (result, ref endPoint);

        String str = Encoding.ASCII.GetString (message, 0, message.Length);
        Console.WriteLine(str);

        lg.curThreads--;
    }

Now, if I limit everything to 1 thread, it works perfectly well... The string I am sending is received correctly. If I use a limit of 10 threads (10 async receives), then I receive a byte array of null values. The size of the buffer is correct (the size of the string I am sending), but all characters are null.

Curiously, this is the behavior with Mono in Mac OS X. It seems it works correctly for Windows machines with Visual Studio.

Thank you for any insight.

EDIT 1: I just installed Visual Studio 2010 Express on a Windows 7 Virtual Machine, and my code works perfectly under windows, when compiled with Microsoft compiler. Can this be a Mono problem? Or a Mac OS X problem?