Applied Motion RS-232 User Manual
Page 279
![background image](/files/766359/content/doc279.png)
279
920-0002 Rev. I
2/2013
Host Command Reference
// send it to the drive
udpClient.Send(sendBytes, sendBytes.Length);
Getting responses back from the drive in C# is a more complicated than VB6. You have two choices: poll for
a response or create a callback function that will provide a true receive event.
Polling is easier to code but less efficient because you must either sit in a loop waiting for an expected
response or run a timer to periodically check for data coming in. Since the choice depends on your programming
style and the requirements of your application, we preset both techniques.
Polling for an incoming packet
The same UdpClient object that you use to send packets can be used to retrieve incoming responses from
the drive. The Available property will be greater than zero if a packet has been received. To retrieve a packet,
assign the Receive property to a Byte array. You must create an IPEndPoint object in order to use the Receive
property.
private void
UDPpoll()
{
// you can call this from a timer event or a loop
if (udpClient.Available > 0)
// is there a packet ready?
{
IPEndPoint
RemoteIpEndPoint =
new
IPEndPoint
(
IPAddress
.Any, 0);
try
{
// Get the received packet. Receive method blocks
// until a message returns on this socket from a remote host,
// so always check .Available to see if a packet is ready.
Byte
[] receiveBytes = udpClient.Receive(
ref
RemoteIpEndPoint);
// strip opcode
Byte
[] SCLstring =
new byte
[receiveBytes.Length - 2];
for
(
int
i = 0; i < SCLstring.Length; i++)
SCLstring[i] = receiveBytes[i + 2];
string
returnData =
Encoding
.ASCII.GetString(SCLstring);
AddToHistory(returnData);
}
catch
(
Exception
ex)
{
// put your error handler here
Console
.WriteLine(ex.ToString());
}
}
}