1

This is inherited code that sometimes fails but I can not figure out why.

using(NetworkStream stream = client.GetStream()) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, message_);
    if(responseHandler_ != null) {
        Message response = (Message) formatter.Deserialize(stream); // <-- fails here
        responseHandler_(response, stream);   
    }
}

I have googled it to death. I have tried seeking suggestions but NetworkStream can not seek.

Edit: It doesn't always fail. Only on occasion. Any help greatly appreciated.

Mal Clarke
  • 147
  • 2
  • 8

2 Answers2

0

In such case I'd suggest copying your NetworkStream to MemoryStream, which can seek - you can find very good examples here.

With MemoryStream, you can reset stream's location after it is serialized

using(var ms = new MemoryStream(stream) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(ms , message_);
    if(responseHandler_ != null) {
        ms.Location = 0;
        Message response = (Message) formatter.Deserialize(ms); 
        responseHandler_(response, ms);   
    }
}
Community
  • 1
  • 1
kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29
  • How do I turn stream = client.GetStream into a byte array that MemoryStream can take in the constructor. I tried this, but after CopyTo the code hangs var output = new MemoryStream(); stream.CopyTo(output); – Mal Clarke May 09 '16 at 10:42
  • @malcie please refer to the hyperlink I added - you can use `CopyTo` method and copy from one stream to another or just a custom method. – kamil-mrzyglod May 09 '16 at 10:43
  • I tried CopyTo but it hangs there. I now have using(client) { using(NetworkStream stream = client.GetStream()) { using(var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream , message_); if(responseHandler_ != null) { memoryStream.Position = 0; Message response = (Message) formatter.Deserialize(memoryStream); responseHandler_(response, memoryStream); } } } } – Mal Clarke May 09 '16 at 12:07
  • Why can't I format this code and Enter submits the comment rather than CR. – Mal Clarke May 09 '16 at 12:10
  • @malcie Can you show how you implemented `CopyTo` and where it hangs exactly? – kamil-mrzyglod May 09 '16 at 12:19
  • I did but it didn't format (above). Not sure how to format as it removes all Carriage Returns??? – Mal Clarke May 09 '16 at 12:36
  • @malcie perform `CopyTo` before `using` statement. TBH I don't think it will be needed anyway. – kamil-mrzyglod May 09 '16 at 12:40
  • I found this [link](http://stackoverflow.com/questions/19328184/tcpclient-getstream-copytomemorystream-stops-application-from-continuing) but I am not sure how to solve it :( – Mal Clarke May 09 '16 at 12:50
0

The problem was at the sending side. Adding a "linger" option solved it.

client.LingerState = new LingerOption (true, 10);

Mal Clarke
  • 147
  • 2
  • 8