Jump to content
Skullcode

TwSocket Udp Client how to receive Bytes Properly ?

Recommended Posts

i use Twsocket as udp Client that is communicating with udpserver 

 

the server sends data in Bytes and the client should Receive This Data in Bytes as well

 

i have tried the following based on what i see in the Demo Sample of OverbyteIcsUdpLstn Demo

 

procedure TMainForm.WSocketDataAvailable(Sender: TObject; Error: Word);
var
aBytes : Tbytes;
begin
wsocket.Receive(aBytes, length(aBytes));
//...
end;

 but this freezes the application and immediately crashed

Share this post


Link to post

Response of Lajos is correct.

But anyway, it is better to use a fixed size array as buffer to avoid allocation freeing a dynamic array as each data packet is coming. So write something like this instead:

procedure TMainForm.WSocketDataAvailable(Sender: TObject; Error: Word);
const
    BUF_SIZE = 1000; // Or whatever size fits your needs
var
    ABytes : array [0..BUF_SIZE] of bytes;
    Len    : Integer;
begin
    Len := WSocket.Receive(@ABytes[0], BUF_SIZE);
    if Len = 0 then
        Exit;
    if Len < 0 then begin
        ShowMessage('Error receiving data');
        Exit;
    end;
    // Process data...
end;

 

Edited by FPiette
  • Thanks 1

Share this post


Link to post

Just a small heads-up; binary transfer requires different handling than text. See

 

 

 

Edited by aehimself

Share this post


Link to post

The onDataAvailable event has knowledge of the data being received, unless you set LineMode to true, you just read all data into a buffer and process it later.  If binary data is not received, that is an application error. 

 

Angus

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×