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; //接收命令返回端口--第一路遠程主從端口:9998 --PC
// --第一路本地主從端口:10000 --消費機 接收命令返回端口
private int ConsumeRecDataPort = Convert.ToInt32(ConfigurationManager.ConnectionStrings["FirstLocalPost"].ConnectionString.ToString()); //接收命令返回端口
private UdpClient UdpRecCmdBack; //接收發送命令返回數據
private Thread ThreadRecCmdBack;
private IPEndPoint RecCmdBackPiont;
public delegate void ConsumeHandler(string msg); //聲明委托
public event ConsumeHandler ConsumeEvent; //聲明事件
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求和
/// </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>
/// 開啟監聽線程
/// </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();
}
}
}
}