Streaming Data between Applications
The following code shows an example of using the Network Streams Library functions to stream data between two applications on different computers.
// Code on computer 1
CNSEndpoint writerEndpoint;
CNSNewScalarEndpoint ("Writer", "//10.0.38.56/Reader", CNSTypeInt32, 100, 0, CNSDirectionWriter, CNSWaitForever, 0, &writerEndpoint);
for (int i = 0; i < 50; i++)
{
int cnsValue = 1; // the value you want to send
CNSWriteScalar (writerEndpoint, CNSWaitForever, cnsValue);
}
CNSFlush(writerEndpoint, CNSWaitForever, CNSFlushAllItemsReadFromStream);
CNSDiscardEndpoint (writerEndpoint);
CNSFinish ();
// Code on computer 2 with IP address 10.0.38.56
CNSEndpoint readerEndpoint;
CNSNewScalarEndpoint ("Reader", "", CNSTypeInt32, 100, 0, CNSDirectionReader, CNSWaitForever, 0, &readerEndpoint);
for (int j = 0; j < 100; j++)
{
int valRead;
CNSReadScalar (readerEndpoint, CNSWaitForever, &valRead);
}
CNSDiscardEndpoint (readerEndpoint);
CNSFinish ();
The example illustrates the following:
- The CNSNewScalarEndpoint function creates a writer endpoint on Computer 1 and a reader endpoint on Computer 2.
Note You can create a writer endpoint and reader endpoint in any order. The CNSNewScalarEndpoint function creates the network stream unless the timeout interval specified for one function expires before the other function executes. - The writer endpoint establishes a connection with the reader endpoint using the otherEndpointUrl parameter.
- Within the writer loop, the CNSWriteScalar function continuously writes the value of the writer endpoint to the stream.
Note If you need to stream more than one data point at a time, you can use the CNSWriteMultipleScalar or CNSWriteMultipleData functions. - Within the reader loop, the CNSReadScalar function continuously reads from the stream.
Note You also can use the CNSReadMultipleScalar or CNSReadMultipleData functions to read from a stream. You can use the read multiple elements function even if you only write single elements and vice versa. - Data continuously streams until the writer loop completes on Computer 1.
- The CNSFlush function transfers all remaining data to the reader endpoint.
- The CNSDiscardEndpoint function discards the endpoint.
- The CNSFinish function discards and cleans up global resources.