0

Using DbgView, i saw that after i receive a Stream, the server then receives 0 bytes like more than 100 times, what is this ? this is new to me, i never saw this happening.

i personally have a feeling it is a client-side issue, could it ?

this is how i receive the stream server-side:

  FMemStream := Socket.ReceiveStream(FMemStreamSize, cbUpdateStreamProgBar);
    try
      doClientReadStreamEnd;
    finally
      FMemStream.Free;
      FInStreamMode := False; // we're not in stream mode anymore
    end;

function TCustomWinSocketHelpher.ReceiveStream(StreamLen: Integer; Callback: TUpdateProgBarProc): TMemoryStream;
const
  ChunkSize = 4096; // 4kb
var
  PData: PByte;
  ReadAmount: Integer;
begin
  Result := TMemoryStream.Create;
  GetMem(PData, StreamLen);
  try
    while StreamLen > 0 do
    begin
      ReadAmount := ReceiveBuf(PData^, ChunkSize);
      if (ReadAmount > 0) then
      begin
        Result.Write(PData^, ReadAmount);
        Callback(ReadAmount); // update gui
        Inc(PData^, ReadAmount); // update PData current position
        Dec(StreamLen, ReadAmount); // update loop condition
      end;
    end;
  finally
    FreeMem(PData);
  end;
end;

on client-side, this is how i send stream:

FClientSocket.Socket.SendStreamEx(RemoteProcedureCalls.Stream);

procedure TCustomWinSocketHelpher.SendStreamEx(Stream: TStream);
begin
  Stream.Seek(0, TSeekOrigin.soBeginning);
  SendStream(Stream);
end;

Here's a photo of how it looks, it should not continue sending after line 5.

enter image description here

5
  • 1
    I don't see the call to debug print in the code above. Typically when a socket read returns 0 that indicates the socket has been closed by the remote end.
    – Dave Rager
    Mar 13, 2013 at 20:47
  • so by remote end you mean it's the client-side fault, right ? if so my i ask, how does it closes the connection just like that ? because server-side isn't being notified about it, and i did notice that if i try to send a string after receiving stream it fails.
    – user1803300
    Mar 13, 2013 at 21:09
  • Yes. When the client is done sending what does it do? Does it close the stream? That would close the connection. Also, how does FMemStreamSize get its value? Is it always the same size or how does it know how many bytes the client is sending? Do the numbers in the output window add up to the total number of bytes in the client data that is sent?
    – Dave Rager
    Mar 13, 2013 at 21:16
  • According to embarcadero, SendStream frees the input stream but does NOT close connection, to free the stream AND close connection, one would call SendStreamAndDrop, which i did not call it. about FMemStreamSize, i deserialize (from json) a class that i send with properties and no, it's not always the same size.
    – user1803300
    Mar 13, 2013 at 21:32
  • 1
    @user1803300: SendStream() does free the stream upon exit, but only if the socket is in a connected state when SendStream() is called, otherwise the stream is NOT freed. So that alone makes SendStream() troublesome to use. I would implement SendStreamEx() to use the same kind of looping that ReceiveStream() uses, and not free the stream at all. Aside from that, Dave's question about the stream size is valid. How does FMemStreamSize gets its value so the receiver knows how many bytes to expect? Mar 13, 2013 at 21:54

1 Answer 1

2

When ReceiveBuf() returns 0, it means the socket has been disconnected by the other party. You are not handling that condition, so you keep looping, getting back 0 again and again. Any value less than 1 is a failed read and needs to be treated as such. If ReceiveBuf() returns -1, an actual read error occurred, but that result can only be returned if the error was WSAEWOULDBLOCK, which is not fatal, or you have an OnError event handler assigned that is setting ErrorCode := 0. Otherwise, ReceiveBuf() would raise an ESocketError exception on a real socket error.

Try this:

function TCustomWinSocketHelpher.ReceiveStream(StreamLen: Integer; Callback: TUpdateProgBarProc): TMemoryStream;
const
  ChunkSize = 4096; // 4kb
var
  PData: PByte;
  ReadAmount: Integer;
begin
  Result := TMemoryStream.Create;
  try
    GetMem(PData, ChunkSize);
    try
      while StreamLen > 0 do
      begin
        ReadAmount := ReceiveBuf(PData^, Min(ChunkSize, StreamLen));
        if ReadAmount < 0 then
        begin
          if WSAGetLastError() = WSAEWOULDBLOCK then
            Continue;
          // an OnError event handler must have disabled an exception being raised
          Exit;
        end;
        if ReadAmount = 0 then
        begin
          // socket disconnected
          raise Exception.Create(''); // or just Exit if you don't mind that the expected data is incomplete
        end;
        Result.WriteBuffer(PData^, ReadAmount);
        Callback(ReadAmount); // update gui
        Dec(StreamLen, ReadAmount); // update loop condition
      end;
    finally
      FreeMem(PData);
    end;
  except
    Result.Free;
    raise;
  end;
end;
5
  • i think there's a flaw in your code, PData size is (allocated) 4kb, where as inside the while loop you keep filling it with 4kb... may i be missing something here ? also, when i receive the stream, i receive it PERFECTLY, but something after receiving it happens, i can't find out... i tried debugging it... -_-
    – user1803300
    Mar 13, 2013 at 22:07
  • 2
    @user1803300: It is not a flaw. You were originally allocating the buffer to the same size as the stream begin sent, reading that entire data into the buffer, then copying the entire buffer to the stream. That is a tremendous waste of memory (stream size * 2 number of bytes allocated in memory). Try sending a large steam and see what happens. Each time ReceiveBuf() is called, the same memory block can be re-used over and over, each read block appended as-is to the end of the stream. That is why I coded it the way I did. Notice I am not advancing the buffer pointer after each read at all. Mar 13, 2013 at 22:21
  • the OnClientRead event is being fired AFTER reading the whole stream which generates this exception(s) chain... the problem is not inside ReceiveStream, i verified this... and my wild guess is that ReceiveStream blocks the thread from processing messages (i think it is blocking the thread from being notified that there's more data to read from the network buffer), how can i over come this ? i need some kind of solution like Application.ProcessMessages, but for a child thread, not the main thread which is the GUI (VCL) thread... any ideas mate ? ;]
    – user1803300
    Mar 15, 2013 at 19:51
  • The OnClientRead event is triggered whenever the socket is in a readable state. That indicates that there is data available to be read from the socket. That might be application data (ReceiveBuf() will return > 0), but it can also be a graceful disconnect notification instead (ReceiveBuf() will return 0). After reading the entire stream in full, the only way OnClientRead will be triggered again is if either new data arrives, or the other party has disconnected. This is not a messaging problem. Mar 15, 2013 at 21:54
  • Remy, can i contact you outside SoF please ?
    – user1803300
    Mar 15, 2013 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.