public partial class FormUDP : Form
{
UdpClient listener = new UdpClient(9871);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
bool ProcessStatus; //process
Thread _UDPthread; //Thread
private void btn_rcve_Click(object sender, EventArgs e)
ThreadStart _process = new ThreadStart(receivemessages);
_UDPthread = new Thread(_process);
ProcessStatus = true;
_UDPthread.Start();
}
private void receivemessages()
MessageBox.Show("start");
while (ProcessStatus)
try
if (listener.Available > 0)
byte[] buffer = listener.Receive(ref groupEP);
///**Start convert **//
TBCastMessageHeader bcastHeader = new TBCastMessageHeader();
IntPtr bcastHeaderPtr;
bcastHeaderPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TBCastMessageHeader)));
Marshal.Copy(buffer, 0, bcastHeaderPtr, buffer.Length);
bcastHeader = (TBCastMessageHeader)(Marshal.PtrToStructure(bcastHeaderPtr, typeof(TBCastMessageHeader)));
switch (bcastHeader.MessageCode)
case 10:
// convert byte to structure and insert into sql database
break;
catch (Exception ex)
{ }
finally { Marshal.FreeHGlobal(bcastHeaderPtr); C.Collect();}
if (ProcessStatus)
Thread.Sleep(new TimeSpan(0, 0, 0, 0, 5)); // 5 miliseconds
// Structure defined
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 0x1)]
public struct TBCastMessageHeader
public ushort MessageCode;
public uint TimeStamp;
public ushort MessageLength;
public sbyte NumberOfDecimals;
public ushort Reserved;