Socket Functions

The Socket functions supply an easy way to interact with other nodes on a computer network, including the ability to send and receive binary data and UTF-8 strings.

Handles

The handle is a built-in data type used to interact with an external resource, including sockets. With a built-in data type, the AeroScript compiler can supply a well-defined interface for socket operations with improved type-checking. For more information, refer to Fundamental Handle Data Type on the Data Types and Variables page.

Open and Close a Socket

You must open a handle before you can use it to communicate with a socket. After you open the handle, you can pass it to other socket operation functions to do many supported operations.

The controller supports sockets that use the Transmission Control Protocol (TCP). These are the main features of TCP:

  • Data that is lost in the network is sent again.
  • Data is received from the network in the same order that it was sent.

You can use the TCP socket types that follow:

  • TCP server: Waits for one or more TCP clients to connect.
  • TCP client: Connects to a TCP server that is waiting for TCP clients to connect.

Open a TCP Server Socket

Use the SocketTcpServerCreate() function to create a TCP server socket.

After you create a TCP server socket, one or more TCP clients can connect to the TCP server. TCP clients that connect are put into a backlog. Use the SocketTcpServerIsClientPending() function to find if a TCP server socket has one or more TCP clients in the backlog.

Use the SocketTcpServerAccept() function to accept a TCP client from the backlog and create a TCP client socket to communicate with the TCP client.

Program Example

var $serverSocket as handle
var $clientSocket as handle

$serverSocket = SocketTcpServerCreate(8080)

while true
    if SocketTcpServerIsClientPending($serverSocket)
        $clientSocket = SocketTcpServerAccept($serverSocket)

        // Communicate with the TCP client.
    end
end

Open a TCP Client Socket

Use the SocketTcpClientCreate() and SocketTcpClientCreateFromHost() functions to connect to a TCP server and create a TCP client socket that you can use for communication with the server.

Use the SocketTcpClientIsConnected() function that follows to determine if a TCP client socket is still connected to another host.

Close a Socket

Use the SocketClose() function to close a TCP server socket or TCP client socket. The controller automatically closes all sockets that you created on a task when the task stops or a task error occurs.

Program Example

var $clientSocket as handle

// Select the applicable create function based on if you know or do not know
// the IP address of the server to which you are connecting.

// If you know the IP address of the server, use the function that follows
// to connect to a server that runs locally.
// 127.0.0.1 is the IPv4 address for localhost.
$clientSocket = SocketTcpClientCreate("127.0.0.1", 8080, 1000)

// If you know the hostname of the server, use the function that follows
// to connect to a server that runs locally.
// The hostname “localhost” is used instead of an IP address.
// The hostname will change to an IPv4 or IPv6 address
// because HostAddressType.Any is specified.
$clientSocket = SocketTcpClientCreateFromHost("localhost", HostAddressType.Any, 8080, 1000)

// Do a check to see if the client socket is connected.
if SocketTcpClientIsConnected ($clientSocket)
    // The client is still connected.
end

// Make sure the socket is closed.
SocketClose($clientSocket)

Read and Write Buffers

Sockets have a buffer so that you can immediately read and write data. Use the SocketGetReadBytesAvailable() and SocketGetWriteBytesAvailable() functions to find the number of bytes that you can read from a socket or write to a socket without waiting.

The controller automatically updates the buffers for reading and writing data. This operation does not execute in real time. The time that it takes for this operation to execute is different for different networks.

Use the SocketSetDataReadTimeout() and SocketSetDataWriteTimeout() functions to configure timeout values for socket read and write operations. The controller generates a task error if you try to read from a socket or write to a socket and the specified operation does not complete before the period specified by the timeout value. By default, read and write operations on a socket are configured to use an infinite timeout value.

Binary Data

When you operate on binary data from a socket, you must determine how the raw bytes of the data are to be interpreted. AeroScript supplies individual functions to access the current socket data stream location based on the specified underlying data type. And, you can use the array-based functions to access contiguous sequences of the socket data.

Supported data types:

  • Float32 - IEEE 754 single-precision floating point
  • Float64 - IEEE 754 double-precision floating point
  • Int8 - signed 8-bit integer
  • Int16 - signed 16-bit integer
  • Int32 - signed 32-bit integer
  • Int64 - signed 64-bit integer
  • Uint8 - unsigned 8-bit integer
  • Uint16 - unsigned 16-bit integer
  • Uint32 - unsigned 32-bit integer

Byte Order of Binary Data

Use the SocketSetDataByteOrder() function to configure the order of the bytes (little endian or big endian) of the binary data that you read or write with a socket. By default, data that you read or write with a socket uses the little endian byte order. Refer to enum SocketByteOrder for the $byteOrder argument values.

Reading Binary Data

Use the SocketReadFloat*(), SocketReadInt*(), and SocketReadUInt*() functions to read binary data from a socket.

To determine if the floating-point values returned by some of these functions are valid, specify the values to the RealIsInfinity() or the RealIsNan() functions. When you use the $numElements argument, the value that you give for the $numElements argument must be at least 1 and less than or equal to the length of the ref $values array argument. If the $numElements argument is less than 1 or greater than the length of the ref $values array argument, then a task error will occur.

Writing Binary Data

Use the SocketWriteFloat*(), SocketWriteInt*(), and SocketWriteUInt*() functions to write binary data to a socket.

When you use the $numElements argument, the value that you give for the $numElements argument must be at least 1 and less than or equal to the length of the $values array argument. If the $numElements argument is less than 1 or greater than the length of the $values array argument, then a task error will occur.

To see an example program that sends an array of values, go to Sockets Array.

Reading Strings

Use the SocketReadString() function to read UTF-8 strings from a socket. To determine if the strings returned by these functions are valid, specify the strings to the StringIsValid() function.

IMPORTANT: When you specify a delimiter to the SocketReadString($socket as handle, $delimiter as string) function, you cannot use an empty delimiter or a delimiter that includes the null-terminator. If you want to use the null-terminator as the delimiter, use the SocketReadString($socket as handle) function overload.

Program Example

// Server.ascript
#define SERVER_PORT 8080

var $serverSocket as handle
var $clientSocket as handle

// Open the port for listening.
$serverSocket = SocketTcpServerCreate(SERVER_PORT)

// Accept a client connection to read from.
$clientSocket = SocketTcpServerAccept($serverSocket)
		
// While connected to the client, keep reading strings.
while SocketTcpClientIsConnected($clientSocket)
    // Check to see if there are any bytes to read.
    if SocketGetReadBytesAvailable($clientSocket) > 0
        // Read a string up to the next space character.
        var $substring as string = SocketReadString($clientSocket, " ")
				
        // Check to see if the string is valid.
        if StringIsValid($substring)
            AppMessageDisplay($substring)
        end
    end
end
		
// Close the connection to the client and the server socket.
SocketClose($clientSocket)
SocketClose($serverSocket)
// Client.ascript
#define SERVER_PORT 8080
				
var $clientSocket as handle

// Create a client connection to the server.
$clientSocket = SocketTcpClientCreate("localhost", SERVER_PORT, 10000)
	
// Send a string with delimiters to be parsed on the server.
// Note that the extra space is needed if we want the last substring to be processed.
SocketWriteString($clientSocket, "hello world goodbye world ")
			
// Close the socket connection.
SocketClose($clientSocket)			

Writing Strings

Use the SocketWriteString() function to write a UTF-8 string to a socket. This function does not write a null terminating character. To write a null terminating character, specify 0 for the $value argument of the SocketWriteUInt8() function.

To see an example program that sends an processes a JSON string, go to Sockets String.

Program Example

var $clientSocket as handle

// Create a client connection to the server.
$clientSocket = SocketTcpClientCreate("localhost", 8080, 10000)
	
// Write a string then append the null terminating character.
SocketWriteString($clientSocket, "Hello World!")
SocketWriteUInt8($clientSocket, 0)
			
// Close the socket connection.
SocketClose($clientSocket)			

Firewall Settings for PC-Based Controllers

If there is an active firewall on the host PC of a PC-based controller, the firewall could block the Socket functions from communicating with client sockets on the network. If you are using a PC-based controller as a socket server, you must configure firewall exceptions before using Socket functions. To configure firewall exceptions for inbound connections, use the procedure that follows.

How to configure firewall exceptions for inbound connections

  1. Open the Start menu. Do a search for Windows Defender Firewall, and open it.
  2. Select Advanced settings. Then select Inbound Rules and click on New Rule in the Actions panel. This opens the New Inbound Rule Wizard.
  3. Select Program, and click Next.
  4. Select This Program Path. Click Browse, and navigate to C:\Program Files\Aerotech\Automation1-iSMC\Bin and select Automation1.Services.Callback.exe. Click Next.
  5. Select Allow the connection, and click Next.
  6. Select which connection types that the remote connection is permitted on. Click Next.
  7. Enter a name for the rule. Click Finish.

IMPORTANT: Outbound connections do not usually require firewall exceptions. If you have connection problems after doing the steps above, repeat the steps for outbound connections by selecting Outbound Rules and then New Rule in Step 2.