Thema: Socket C&S

Einzelnen Beitrag anzeigen

tomkupitz

Registriert seit: 26. Jan 2011
323 Beiträge
 
Delphi 11 Alexandria
 
#20

AW: Socket C&S

  Alt 9. Feb 2018, 16:52
Sooo...

Server:

Code:
procedure TForm1.Button1Click(Sender: TObject);
var bmp: TBitmap;
    buf: array of Byte;
    res, len, bufidx, bufsize: Integer;

    procedure BmpToBuf;
    var i, x, y, w, h: Integer;
        p: PByteArray;

    begin
      w:=bmp.Width;
      h:=bmp.Height;

      bmp.PixelFormat:=pf24bit;

      i:=1234;

      Move(i, buf[0], sizeof(Integer));

      Move(w, buf[sizeof(Integer)], sizeof(Integer));
      Move(h, buf[2*sizeof(Integer)], sizeof(Integer));

      i:=sizeof(Integer)+2*sizeof(Integer);

      for y:=0 to h-1 do
      begin
        p:=bmp.Scanline[y];
        Move(p[0], buf[i], w*3);
        inc(i, w*3);
      end;
    end;

begin
  bmp:=<MacheinScreenshotvomFenster>(Handle);

  len:=sizeof(Integer)+2*sizeof(Integer)+bmp.Height*bmp.Width*3;

  if len mod 1024 <> 0 then
    inc(len, 1024-(len mod 1024));

  SetLength(buf, len);
  BmpToBuf;

  bmp.Free;

  if ServerSocket.Socket.ActiveConnections>0 then
  begin
    bufidx:=0; bufsize:=Length(buf);

    while bufsize>0 do
    begin
      repeat
        res:=ServerSocket.Socket.Connections[0].SendBuf(buf[bufidx], Min(1024, bufsize));
        if res<>1024 then <MacheinePause>(50);
      until res<>-1;

      inc(bufidx, Min(1024, bufsize));
      dec(bufsize, Min(1024, bufsize));
    end;
  end;

  Finalize(buf);
end;
Client:

Code:
var
  buf: array of Byte;
  sz: Integer = -1;

  id, wi, hi: Integer;

procedure TForm1.ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket);
var bmp: TBitmap;
    len, res: Integer;

    procedure BufToBmp;
    var i, x, y, w, h: Integer;
        p: PByteArray;

    begin
      bmp:=TBitmap.Create;
      bmp.PixelFormat:=pf24Bit;

      Move(buf[0], i, sizeof(Integer));

      Move(buf[sizeof(Integer)], w, sizeof(Integer));
      Move(buf[2*sizeof(Integer)], h, sizeof(Integer));

      bmp.Width:=w;
      bmp.Height:=h;

      i:=sizeof(Integer)+2*sizeof(Integer);

      for y:=0 to h-1 do
      begin
        if i+w*3-1>Length(buf) then
          Break;

        p:=bmp.Scanline[y];
        Move(buf[i], p[0], w*3);
        inc(i, w*3);
      end;
    end;

begin
  len:=Length(buf);

  SetLength(buf, len+1024);

  res:=Socket.ReceiveBuf(buf[len], 1024);

  if (sz=-1) and (Length(buf)>=sizeof(Integer)+2*sizeof(Integer)) then
  begin
    Move(buf[0], id, sizeof(Integer));

    Move(buf[sizeof(Integer)], wi, sizeof(Integer));
    Move(buf[2*sizeof(Integer)], hi, sizeof(Integer));

    if id=1234 then
    begin
      sz:=sizeof(Integer)+2*sizeof(Integer)+hi*wi*3;

      if sz mod 1024 <> 0 then
        inc(sz, 1024-(sz mod 1024));
    end;
  end;

  if (sz>-1) and (Length(buf)=sz) then
  begin
    BufToBmp;
    Image1.Picture.Bitmap.Assign(bmp);
    bmp.Free;

    Finalize(buf);
    sz:=-1;
  end;
end;
  Mit Zitat antworten Zitat