开发者

C# Sockets Sending Serialized Data

I am having trouble sending serialized data over a TCP/IP socket connection.

My send function looks like this:

public void SendData(NetworkConnection connection, ReplicableObject ro) {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, ro);

            ms.WriteTo(connection.TcpStream);
            connection.TcpStream.Flush();

            ms.Close();
        }

I'm aware that currently TcpStream.Flush() doesn't do anything. That's not my issue, anyway.

On the receiving (client) end, the reader looks like this:

byte[] readBuffer = new byte[8192];
            wor开发者_开发问答ldMapStream = worldMapConnection.GetStream();
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            IsConnectedToWorldMap = true;
            while (true) {
                try {
                    do {
                        int bytes = worldMapStream.Read(readBuffer, 0, readBuffer.Length);
                        ms.Write(readBuffer, 0, bytes);
                    }
                    while (worldMapStream.DataAvailable);

                    try {
                        ReplicableObject ro = (ReplicableObject) bf.Deserialize(ms);
                        ro = ro;
                    }
                    catch (Exception e) {
                        e = e;
                    }
                }

The strange ro = ro and e = e lines are just there so I can add a breakpoint.

My problem is this: The read always fails. I get an exception caught, and the message explains that the end of the stream was reached before parsing was completed. Now, I understand that the data might not all arrive in one chunk, but I haven't cleared the memory stream on catching an exception, so the next chunk should just add the remaining data onto the end of it, right? But this doesn't work, apparently.

So, what am I doing wrong? Thanks in advance. :)

P.S. I understand that WCF is the better alternative to this; but unfortunately I can't use that in this project.


Here we go:

while (worldMapStream.DataAvailable);

Should be:

while(bytes>0);

Which also means moving bytes outside the loop.

DataAvailable just means "right now, at the NIC". It doesn't tell you whether more is coming or not. Also, you should ony Write when bytes>0 too; to be honest a while loop is easier here :)

Then; after filling ms set ms.Position = 0 to rewind te stream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜