.NET blocking socket read until X bytes are available?

落花浮王杯 提交于 2019-12-01 20:38:28

Something, somewhere is going to have to loop. After all, multiple socket reads could be required.

I believe that BinaryReader.Read will keep looping until either it's read as much as you've asked for or hit the end of the stream, but assuming you would want to throw an exception if you reached the end of the stream, I'd write personally write a separate method. It's easy enough to implement in one place and reuse, after all.

Socket.Available will do the trick, if you don't mind a tight loop with a wait in?

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.available%28VS.71%29.aspx

You need to buffer the data yourself, the specification of read is that it can read any amount between 1 bytes and the buffer size when it returns.

it sounds like the yield statement could suit this scenario just fine.

i.e. say there's a loop watching the incomming stream, and once you hit each length number, you give back control to the caller via 'yield' to IEnumerable / foreach.

Perhaps the yield could in turn signal via an event for an alternative decoupling to IEnumerable. I find IEnumerable to be convenient though.

Klinger

Take a look on the following link: http://blog.stephencleary.com/2009/04/tcpip-net-sockets-faq.html

In this link you will find excelent info on sockets and also a library.

The one thing I would make sure to implement is a timeout mechanism in order to avoid getting stuck when the network goes bad.

well, kind stinks we have to write a loop but I would have liked nonetheless if someone put a loop in this forum post so I could have cut and paste it real quick...here was mine(and yeah, the i thing I would rather base in time but it is only for unit tests and they control a simulated server so I don't care that much+ I don't want my unit test to get stuck on a failure when it calls my Read method)

        int numBytes = 0;
        int i = 0;
        while(numBytes != length)
        {
            numBytes += latestClient.Receive(body, numBytes, length-numBytes, SocketFlags.None);                
            if(i == 10000)
                throw new Exception("Could not read enough data.  read="+numBytes+" but expected="+length);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!