Connecting to the API
- Open a TCP socket.
- Authentication: Login by sending a CSTA StartApplicationSession request in XML format (as a string) to the socket.
- CSTA request, responses and CSTA events are received as strings from the TCP socket. You need to split up the received text into XML document strings and then deserialized into a typed object if needed.
tip
The TCP client support XML requests, responses and events. They follow the CSTA format in the ECMA-323 CSTA Standard.
.NET Sample Client
This sample client is written in C# .NET using the NetCoreServer library available at nuget.
It provides the basis for setting up a TCP client, so you can begin communication with the Uni-tel CSTA API via TCP.
public class TcpClient : NetCoreServer.TcpClient
{
private const string MESSAGE_TERMINATOR = "\0";
private readonly Action<object> _newMessageFunc;
private readonly Serializer _serializer;
private string _dataReceived = string.Empty;
public TcpClient(Action<object> newMessageFunc, string address, int port) : base(address, port)
{
_newMessageFunc = newMessageFunc;
_serializer = new Serializer();
}
public void SendAsync<T>(T message)
{
Console.WriteLine($"Sending {message.GetType()} message ");
base.SendAsync(_serializer.Serialize(message) + MESSAGE_TERMINATOR);
}
protected override void OnConnected()
{
Console.WriteLine($"TcpClient connected");
ReceiveAsync();
base.OnConnected();
}
protected override void OnDisconnected()
{
Console.WriteLine($"TcpClient disconnected");
base.OnDisconnected();
}
protected override void OnReceived(byte[] buffer, long offset, long size)
{
var chunk = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
_dataReceived += chunk;
while (_dataReceived.Contains(MESSAGE_TERMINATOR))
{
var index = _dataReceived.IndexOf(MESSAGE_TERMINATOR, StringComparison.Ordinal);
var message = _dataReceived.Substring(0, index);
_dataReceived = _dataReceived.Substring(index + 1);
try
{
var convertedMessage = _serializer.Deserialize(message);
_newMessageFunc(convertedMessage);
}
catch (Exception ex)
{
Console.WriteLine($"Invalid XML document? Exception: {ex.Message}. XML = {message}");
}
}
}
protected override void OnError(SocketError error)
{
Console.WriteLine($"TCP client returned error code: '{error}'");
}
}