TWSocket.ReceiveFrom

From Overbyte
Jump to navigation Jump to search

Main page -> ICS component reference -> TWSocket -> ReceiveFrom

Definition

  function ReceiveFrom(Buffer:Pointer; BufferSize:integer; var from:TSockAddr; 
                       var fromSize:integer):integer;

Description

ReceiveFrom is used in the OnDataAvailable-Event to fetch the received data and information about the sender.

The required parameters are: 1) buffer where the data will be placed 2) the size of the buffer 3) TSockAddr variable 4) the size of the TSockAddr

The return value of ReceiveFrom specifies how many bytes were actually read and placed in the buffer and the information about the sender is placed in the "from" variable. If the buffer is too small, OnDataAvailable will occur again until all data is received.

If the return value is 0 the connection the data should be read from has been closed and a value of less than 0 means an error occurred and the SOCKET_ERROR constant value will be returned. In order to retrieve the actual error code you must check the LastError property immediately, before any other call might lead to another error.

If the LastError error code is WSAE_WOULD_BLOCK, it means ReceiveFrom was called at a point in time when the system was not ready to process the call. Most likely you can ignore this error condition.

Example

  procedure WSocket1OnDataAvailable(Sender: TObject; ErrCode: Word);
  var 
   buf:array[1..64] of byte;
   len, fromSize:integer;
   from:TSockAddr;
  begin
    if ErrCode <> 0 then Exit;
    fromSize:=sizeOf(from); 
    len:=ReceiveFrom(@buf, sizeof(buf), from, fromSize);
    if (len > 0) then
      // here your procesing of the data will take place
  end;

Best practices

  • never do any message processing like Application.ProcessMessages or GetMessage inside an event handler, since it will raise the same event again for the very same data.
  • if the data received needs lengthy processing, a separate thread for data processing might be a good idea since further data can only be received after the event has been processed completely. In most cases a separate thread is not necessary.

How to