SocketAsyncEventArgs buffer is full of zeroes

半腔热情 提交于 2020-01-22 20:09:16

问题


I'm writing a message layer for my distributed system. I'm using IOCP, ie the Socket.XXXAsync methods.

Here's something pretty close to what I'm doing (in fact, my receive function is based on his): http://vadmyst.blogspot.com/2008/05/sample-code-for-tcp-server-using.html

What I've found now is that at the start of the program (two test servers talking to each other) I each time get a number of SAEA objects where the .Buffer is entirely filled with zeroes, yet the .BytesTransferred is the size of the buffer (1024 in my case).

What does this mean? Is there a special condition I need to check for? My system interprets this as an incomplete message and moves on, but I'm wondering if I'm actually missing some data. I was under the impression that if nothing was being received, you'd not get a callback. In any case, I can see in WireShark that there aren't any zero-length packets coming in.

I've found the following when I Googled it, but I'm not sure my problem is the same: http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/40fe397c-b1da-428e-a355-ee5a6b0b4d2c

http://go4answers.webhost4life.com/Example/socketasynceventargs-buffer-not-ready-121918.aspx


回答1:


I am sure not what is going on in the linked example. It appears to be using asynchronous sockets in a synchronous way. I cannot see any callbacks or similar in the code. You may need to rethink whether you need synchronous or asynchronous sockets :).

To the problem at hand stems from the possibility that your functions are trying to read/write to the buffer before the network transmit/receive has been completed. Try using the callback functionality included in the async Socket. E.g.

// This goes into your accept function, to begin receiving the data
    socketName.BeginReceive(yourbuffer, 0, yourbuffer.Length,
        SocketFlags.None, new AsyncCallback(OnRecieveData), socketName);

// In your callback function you know that the socket has finished receiving data
// This callback will fire when the receive is complete.
private void OnRecieveData(IAsyncResult input) {
    Socket inSocket = (Socket)input.AsyncState; // This is just a typecast
    inSocket.EndReceive(input);

    // Pull the data out of the socket as you already have before.
    // state.Data.Write ......
}


来源:https://stackoverflow.com/questions/10836380/socketasynceventargs-buffer-is-full-of-zeroes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!