Eszee
Eszee

Reputation: 262

Delphi memory stream to server

I am working on creating a chat program. But for some reason my stream won't come through. Could someone check my code and tell me what I am doing wrong?

Client side:

procedure TForm1.Button1Click(Sender: TObject);
var
  myStream : TMemoryStream;
  chat : String;
begin
  //Creating a stream
  chat := 'bladibla';
  myStream := TMemoryStream.Create();
  myStream.Size := Length(Chat);
  myStream.WriteBuffer(Pointer(Chat)^, Length(Chat));

  //Resetting the stream position
  myStream.Position := 0;

  //Sending the stream
  TcpClient1.Active := true;
  TcpClient1.SendStream(myStream);
  TcpClient1.Active := false;

  //Free the stream
  myStream.Free;
end;

Server Side:

procedure TForm1.TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
var
  chat : string;
begin
//Receives the message from the client
  ClientSocket.ReceiveBuf(Pointer(Chat)^,Length(Chat),0);

  memo1.Lines.Add(chat);
  memo1.Lines.Add('------');
end;

Upvotes: 0

Views: 1494

Answers (1)

Chris Rolliston
Chris Rolliston

Reputation: 4808

If you're using D2009 or later, then when sending, you're cutting the data in half. Also, given you will ultimately be reading the data with ReceiveBuf, it would probably be sensible to prepend a length marker. Less substantively, you also don't need to set the memory stream's Size up front, and should wrap the stream usage in a try/finally block:

procedure TForm1.Button1Click(Sender: TObject);
var
  myStream : TMemoryStream;
  chat : String;
  Len: Int32;
begin
  //Creating a stream
  chat := 'bladibla';
  myStream := TMemoryStream.Create();
  try
    Len := Length(Chat);
    myStream.WriteBuffer(Len, SizeOf(Len));
    myStream.WriteBuffer(Pointer(Chat)^, Len * SizeOf(Char));

    //Resetting the stream position
    myStream.Position := 0;

    //Sending the stream
    TcpClient1.Active := true;
    TcpClient1.SendStream(myStream);
    TcpClient1.Active := false;
  finally
    //Free the stream
    myStream.Free;
  end;
end;

In the case of the receiving code, you haven't pre-allocated the Chat buffer. As such, Length(Chat) will be 0. Given my suggested code above, we can read off the length marker first:

procedure TForm1.TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
var
  chat : string;
  Len: Int32;
begin
  //Receives the message from the client
  ClientSocket.ReceiveBuf(Len, SizeOf(Len),0);
  SetLength(Chat, Len);
  ClientSocket.ReceiveBuf(Pointer(Chat)^,Len * SizeOf(Char),0);

  memo1.Lines.Add(chat);
  memo1.Lines.Add('------');
end;

Lastly... the components used in this code are deprecated, so it might be an idea to investigate Indy instead.

Upvotes: 1

Related Questions