Delphi内存流到服务器

时间:2013-11-04 11:17:54

标签: memorystream delphi

我正在制作聊天程序。但由于某种原因,我的流不会通过。有人可以查看我的代码并告诉我我做错了吗?

客户方:

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;

服务器端:

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;

1 个答案:

答案 0 :(得分:1)

如果您使用的是D2009或更高版本,那么在发送时,您将数据减半。另外,鉴于您最终将使用ReceiveBuf读取数据,因此预先设置长度标记可能是明智的。在实质上,您也不需要预先设置内存流的Size,并且应该将流使用包装在try / finally块中:

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;

在接收代码的情况下,您尚未预先分配Chat缓冲区。因此,Length(Chat)将为0.鉴于我上面建议的代码,我们可以先读取长度标记:

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;

最后......此代码中使用的组件已弃用,因此调查Indy可能是一个想法。