Using System;
Using System. Collections. Generic;
Using System. Configuration;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;
Using System. Threading;
Namespace LcSoftCard. Service
{
Public class UDPConsumeServiceDS
{
Private bool flag;
Public bool Flag
{
Get {return flag ;}
Set {flag = value ;}
}
Private IPEndPoint SendPoint;
Private const int ConsumeRecCmdBackPort = 9998; // receive command return port -- first remote Master/Slave port: 9998 -- PC
// -- First-line Local Master/Slave port: 10000 -- consumer machine receiving command return port
Private int ConsumeRecDataPort = Convert. ToInt32 (ConfigurationManager. ConnectionStrings ["FirstLocalPost"]. ConnectionString. ToString (); // receive command return port
Private UdpClient UdpRecCmdBack; // receives the data returned by the sending command
Private Thread ThreadRecCmdBack;
Private IPEndPoint RecCmdBackPiont;
Public delegate void ConsumeHandler (string msg); // declare the delegate
Public event ConsumeHandler ConsumeEvent; // declare an event
Public void SendCommand (string cmd, string ip)
{
String rst = cmd. ToUpper () + AscSum (cmd. ToUpper ());
SendPoint = new IPEndPoint (IPAddress. Parse (ip), ConsumeRecDataPort );
Byte [] SendData = Encoding. ASCII. GetBytes (rst );
Uint IOC_IN = 0x80000000;
Uint IOC_VENDOR = 0x18000000;
Uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
UdpRecCmdBack. Client. IOControl (int) SIO_UDP_CONNRESET, new byte [] {Convert. ToByte (false)}, null );
UdpRecCmdBack. Send (SendData, SendData. Length, SendPoint );
}
/// <Summary>
/// ASCII summation
/// </Summary>
/// <Param name = "str"> </param>
/// <Returns> </returns>
Public string AscSum (string str)
{
Int sum = 0;
String rst;
If (str. Length = 0) return "00 ";
System. Text. ASCIIEncoding asciiEncoding = new System. Text. ASCIIEncoding ();
For (int I = 0; I <str. Length; I ++)
{
Sum + = (int) asciiEncoding. GetBytes (str) [I];
}
Sum % = 0x100;
Rst = sum. ToString ("x ");
If (rst. Length <2) rst = "0" + rst;
Return rst. ToUpper ();
}
Public void StartRecCmdBackListen ()
{
While (true)
{
Byte [] recData = UdpRecCmdBack. Receive (ref RecCmdBackPiont );
String ReadStr = BitConverter. ToString (recData). Replace ("-","");
ReadStr = Encoding. ASCII. GetString (recData );
Flag = true;
If (ConsumeEvent! = Null)
{
ConsumeEvent (ReadStr );
}
}
}
/// <Summary>
/// Enable the listening thread
/// </Summary>
Public void ConsumeRun ()
{
UdpRecCmdBack = new UdpClient (ConsumeRecCmdBackPort );
ThreadRecCmdBack = new Thread (new ThreadStart (StartRecCmdBackListen ));
ThreadRecCmdBack. IsBackground = true;
ThreadRecCmdBack. Start ();
}
Public void ConsumeStop ()
{
If (ThreadRecCmdBack! = Null)
{
ThreadRecCmdBack. Abort ();
UdpRecCmdBack. Close ();
}
}
}
}