Back to top

KAS to receive data via TCP/IP connections

This article provides a simple example of receiving data via TCP. 

  1. Import the attached program.
  2. Set EN_CONNECTION=true

The KAS system now listens for TCP connections from a remote device.

When the connection is established the device can send strings to the KAS IDE.

// If EN_CONNECTION = 0, close the socket
// Set Port Number and Amount of Characters to receive with each call of TcpReceive
if not(EN_CONNECTION) then
   if mysocket<>0 then
      Inst_TcpClose(true,mysocket);
      Inst_TcpClose(false,mysocket);
      mysocket:=0;
   end_if;
   mycounter:=1;
   KAS_TCP_PORT:=1234;
   MAX_CHAR_TO_RECEIVE:=200;
   return;
end_if;

case mycounter of

1: //Create a Socket by perofrming an open and bond operation 
   Inst_TcpListen(true,KAS_TCP_PORT, 2(*DINT*) );
   mycounter := mycounter + 1;  

2: // Wait for function block completion and provide the ID for the Listening Socket
   Inst_TcpListen(true,KAS_TCP_PORT, 2(*DINT*) );
   if Inst_TcpListen.Done then
      Inst_TcpListen(false,1234, 2(*DINT*) );
      mycounter := mycounter + 1;
   end_if;

3: // Start function block to accept the Listening Client ID
   Inst_TcpAccept(true,Inst_TcpListen.ListenID);
   mycounter := mycounter + 1;

4: // Wait for function block completion, store Client ID in mysocket  
   Inst_TcpAccept(true,Inst_TcpListen.ListenID);
   if Inst_TcpAccept.Done then
      mysocket:=Inst_TcpAccept.ID;
      mycounter := mycounter + 1;
      Inst_TcpAccept(false,Inst_TcpListen.ListenID);
   end_if;
 
5: // Start function block to receive characters over the socket connection
   Inst_TcpReceive(true,mysocket,MAX_CHAR_TO_RECEIVE);
   mycounter := mycounter + 1;

6: // Wait for characters to be received, store in mystring
   Inst_TcpReceive(true,mysocket,MAX_CHAR_TO_RECEIVE);
   if Inst_TcpReceive.Done then
      mystring:=Inst_TcpReceive.Data;
      Inst_TcpReceive(false,mysocket,MAX_CHAR_TO_RECEIVE);
      mycounter := mycounter + 1;
   end_if;
7:
   mycounter := 5;

end_case;
Attachment