Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   transformar archivo binario a texto (https://www.clubdelphi.com/foros/showthread.php?t=61899)

pakitto 26-11-2008 13:22:16

transformar archivo binario a texto
 
Hola a todos.
A ver si me podéis echar una mano. Estoy realizando una aplicación cliente servidor con indy 10, por la que tengo que enviar archivos, los archivos lo envio en formato binario, y parece que todo va bien, pues el archivo recibido pesa lo mismo que el enviado, el problema me viene cuando paso el archivo a texto, que me corta el texto al principio y mete basura al final.

Este es el código del servidor, donde recibo el archivo y como hago la transformación a texto.


{ Server: Ejemplo de cómo transferir un archivo de cualquier tipo atravez de Internet
------- Programa Servidor --------
Puerto de escucha: 8529
}

unit Server1;

interface

uses
Windows, Messages, SysUtils, {Variants,} Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdTCPServer, Gauges,IdContext,
IdCustomTCPServer, IdGlobal, StdCtrls;

type
TForm1 = class(TForm)
Server1: TIdTCPServer; //TCP Server, palete Indy Servers
Gauge1: TGauge;
Memo1: TMemo; //Barra de progreso, paleta Samples.
procedure Server1Execute(AContext: TIdContext);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Server1Execute(AContext: TIdContext);
var


s: string;
F: TFileStream;
BufSize,i : Integer;
A:file of byte; //Logico del archivo a recibir
buff : TidBytes;
Buffer:Array [0..1023] of byte; //Buffer de escritura. (1024 bytes)
Leidos, Longitud: Integer; //Contadores.
begin
AssignFile(A,'recibe.dat');
F := TFileStream.Create( ExtractFilePath( Application.ExeName ) +'prueba.txt', fmCreate ); //Asigna el nombre fisico al Lógico en el directorio local.
F.Position:=0;
Longitud:= strtoint(Acontext.Connection.IOHandler.Readln); //Recibo la logitud del archivo a recibir primero, Esto lo envia el cliente.
Leidos:= 0; //Inicializo Leidos.
rewrite(A); //Apertura del Archivo en disco, si no existe se crea, si existe se sobreescribe.
Gauge1.MinValue:=Leidos; //Inicializo la barra de prograso.
Gauge1.Progress:=Gauge1.MinValue;
Gauge1.MaxValue:=Longitud;
while Longitud > 0 do //Mientras no se llegue a la longitud esperada
begin

Leidos:= strtoint(AContext.Connection.IOHandler.Readln); //Recibo del cliente cuántos bytes transmite.
AContext.Connection.IOHandler.ReadBytes(buff,sizeOf(Buffer),false);

BytesToRaw(Buff, Buffer, sizeOf(Buffer));

s:=bytestostring(buff,sizeof(buff));

F.Write(s[1],length(s));

BlockWrite(A,Buff,Leidos); //Escribo en el archivo todo el buffer.

Gauge1.Progress:=Gauge1.Progress + Leidos; //Actualizo la barra de progreso.
Longitud:= Longitud - Leidos; //Descuento longitud.


end; { While }



try
CloseFile(A);
F.Free; //Cierro el archivo.
except
Showmessage('No he cerrado el fichero');
end;

end; { Server1Execute }




procedure TForm1.FormCreate(Sender: TObject);
begin
Server1.Active:=true; //Activo el Servidor al arrancar la aplicación.
end;

end.


Gracias por vuestro tiempo.

enecumene 26-11-2008 14:09:45

Me tomé la molestia de colocar tu código entre las etiquetas delphi, por favor, úsalas con más frecuencia ;).

Código Delphi [-]
{ Server: Ejemplo de cómo transferir un archivo de cualquier tipo atravez de Internet
------- Programa Servidor --------
Puerto de escucha: 8529
}

unit Server1;

interface

uses
  Windows, Messages, SysUtils, {Variants,} Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdComponent, IdTCPServer, Gauges,IdContext,
  IdCustomTCPServer, IdGlobal, StdCtrls;

type
  TForm1 = class(TForm)
    Server1: TIdTCPServer;  //TCP Server, palete Indy Servers
    Gauge1: TGauge;
    Memo1: TMemo;         //Barra de progreso, paleta Samples.
    procedure Server1Execute(AContext: TIdContext);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Server1Execute(AContext: TIdContext);
var


s: string;
F: TFileStream;
BufSize,i : Integer;
A:file of byte;                                 //Logico del archivo a recibir
buff : TidBytes;
Buffer:Array [0..1023] of byte;         //Buffer de escritura. (1024 bytes)
Leidos, Longitud: Integer;             //Contadores.
begin
  AssignFile(A,'recibe.dat');
F := TFileStream.Create( ExtractFilePath( Application.ExeName ) +'prueba.txt', fmCreate ); //Asigna el nombre fisico al Lógico en el directorio local.
  F.Position:=0;
Longitud:= strtoint(Acontext.Connection.IOHandler.Readln); //Recibo la logitud del archivo a recibir primero, Esto lo envia el cliente.
  Leidos:= 0;                                     //Inicializo Leidos.
rewrite(A); //Apertura del Archivo en disco, si no existe se crea, si existe se sobreescribe.
  Gauge1.MinValue:=Leidos;                        //Inicializo la barra de prograso.
  Gauge1.Progress:=Gauge1.MinValue;
  Gauge1.MaxValue:=Longitud;
  while Longitud > 0 do                           //Mientras no se llegue a la longitud esperada
  begin

    Leidos:= strtoint(AContext.Connection.IOHandler.Readln);  //Recibo del cliente cuántos bytes transmite.
    AContext.Connection.IOHandler.ReadBytes(buff,sizeOf(Buffer),false);

    BytesToRaw(Buff, Buffer, sizeOf(Buffer));

    s:=bytestostring(buff,sizeof(buff));

    F.Write(s[1],length(s));

    BlockWrite(A,Buff,Leidos);   //Escribo en el archivo todo el buffer.

    Gauge1.Progress:=Gauge1.Progress + Leidos;     //Actualizo la barra de progreso.
    Longitud:= Longitud - Leidos;                  //Descuento longitud.


  end;  { While }



  try
  CloseFile(A);
  F.Free;             //Cierro el archivo.
  except
  Showmessage('No he cerrado el fichero');
  end;

end; { Server1Execute }




procedure TForm1.FormCreate(Sender: TObject);
begin
Server1.Active:=true;  //Activo el Servidor al arrancar la aplicación.
end;

end.

Saludos.


La franja horaria es GMT +2. Ahora son las 13:10:29.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi