{$X+,V-,B-}
program RecHello2;

{ Simple IPX demonstration program, that uses one receive ESR.

  Run this program on 1 workstation, run S_HELLO or S1_HELLO on another.
  S_HELLO will send "hello world" messages,
  this workstation will receive them.  }

uses crt,nwMisc,nwIPX;

CONST IOSocket=$5678;

Var ReceiveEcb    :Tecb;
    IpxHdr        :TipxHeader;
    socket        :word;
    buf           :array[1..546] of byte;
    t             :byte;
    ReceivedBufLen:word;
    PacketReceived:boolean;

    RecString     :string;

    NewStack:array[1..1024] of word;  { !! used by ESR }
    StackBottom:word;                 { !! used by ESR }


{$F+}
Procedure ListenESRhandler(Var p:Tpecb);
begin
RecString[0]:=chr(p^.fragment[2].size);
move(p^.fragment[2].address^,RecString[1],byte(RecString[0]));
PacketReceived:=true;
IPXListenForPacket(ReceiveECB);
end;
{$F-}

{$F+}
Procedure ListenESR; assembler;
asm { ES:SI are the only valid registers when entering this procedure ! }
    mov dx, seg stackbottom
    mov ds, dx

    mov dx,ss  { setup of a new local stack }
    mov bx,sp  { ss:sp copied to dx:bx}
    mov ax,ds
    mov ss,ax
    mov sp,offset stackbottom
    push dx    { push old ss:sp on new stack }
    push bx

    push es    { push es:si on stack as local vars }
    push si
    mov  di,sp

    push ss    { push address of local ptr on stack }
    push di
    CALL ListenEsrHandler

    add sp,4   { skip stack ptr-copy }
    pop bx     { restore ss:sp from new stack }
    pop dx
    mov sp,bx
    mov ss,dx
end;
{$F-}


begin
IF NOT IpxInitialize
 then begin
      writeln('Ipx needs to be installed.');
      halt(1);
      end;
socket:=IOSocket;
IF NOT IPXopenSocket(Socket,SHORT_LIVED_SOCKET)
 then begin
      writeln('IPXopenSocket returned error# ',nwIPX.result);
      halt(1);
      end;

PacketReceived:=False;
{ Empty receive buffer (ReceiveEcb.fragment[2].address^) }
FillChar(buf,546,#0);

{ Setup ECB and IPX header }
IPXsetupListenECB(Addr(ListenESR),IOsocket,@buf,546,
                  IpxHdr,ReceiveEcb);

IPXListenForPacket(ReceiveECB);

REPEAT

IPXrelinquishControl;

IF PacketReceived { ESR has signalled that a packet has been received }
 then begin
      writeln(RecString);
      PacketReceived:=false;
      end;

UNTIL KeyPressed;

IF NOT IPXcloseSocket(IOsocket)
 then writeln('IPXcloseSocket returned error# ',nwIPX.result);

end.