气体仪器(服务)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoRefund
{
    public partial class Service1 : ServiceBase
    {
        #region Socket 服务器
        //定义回调:解决跨线程访问问题
        private delegate void SetTextValueCallBack(string strValue);
        //定义接收客户端发送消息的回调
        private delegate void ReceiveMsgCallBack(string strReceive);
        //声明回调
        private SetTextValueCallBack setCallBack;
        //声明
        private ReceiveMsgCallBack receiveCallBack;
        //定义回调:给ComboBox控件添加元素
        private delegate void SetCmbCallBack(string strItem);
        //声明
        private SetCmbCallBack setCmbCallBack;
        //定义发送文件的回调
        private delegate void SendFileCallBack(byte[] bf);
        //声明
        private SendFileCallBack sendCallBack;

        //用于通信的Socket
        Socket socketSend;
        //用于监听的SOCKET
        Socket socketWatch;

        //将远程连接的客户端的IP地址和Socket存入集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        //接收客户端发送消息的线程
        Thread threadReceive;
        //创建监听连接的线程
        Thread AcceptSocketThread;
        //创建用于监听SOcket是否关闭的线程
        Thread closeSocket;
        //创建用于发送数据的线程
        Thread SendMsgThread;
        public string FirstOrderGas = "03 01 4E 00 02"; //氨气
        public string SecondOrderGas = "03 02 4E 00 02"; //硫化氢
        public string FourOrderGas = "03 04 4E 00 02"; // 氧气
        public string temperature = "03 00 1F 00 02"; // 温度     
        public string humidity = "03 00 21 00 02";//湿度
        #endregion
        System.Threading.Timer recordTimer;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            IntialOpenMRecord();
        }

        protected override void OnStop()
        {
            try
            {
                if (recordTimer != null)
                {
                    recordTimer.Dispose();
                }
            }
            catch (Exception e)
            {
                log.log("自动停止:" + e.Message + ",时间" + DateTime.Now);
            }
        }
        Log log = new Log("E:\\AutoRefund" + @"/log/Log.txt");
        #region  服务器监听端口打开
        private void IntialOpenMRecord()
        {
            #region 设置服务器监听的端口
            try
            {
                
                //当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取ip地址
                IPAddress ip = IPAddress.Parse(ConfigurationManager.AppSettings["IP"].Trim());
                //创建端口号
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(ConfigurationManager.AppSettings["Port"].Trim()));
                //绑定IP地址和端口号
                socketWatch.Bind(point);
                log.log("监听成功" + "开启时间" + DateTime.Now );

                //开始监听:设置最大可以同时连接多少个请求
                socketWatch.Listen(10);
                //创建线程
                AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
                AcceptSocketThread.IsBackground = true;
                AcceptSocketThread.Start(socketWatch);
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
                timer.Interval = int.Parse(ConfigurationManager.AppSettings["SJ"].Trim());//每5秒执行一次
                timer.Enabled = true;
                
            }
            catch (Exception e)
            {
                log.log("监听出错:" + e.Message + ",时间"+DateTime.Now );
            }
            #endregion

          
        }
        #endregion
        private void closeSocketJT(object obj) //监听是否正常关闭的线程
        {
            Socket socketSend = obj as Socket;
            try
            {
                while (true)
                {
                    if (socketSend.Poll(10, SelectMode.SelectRead))
                    {
                        string strReceiveMsg = "断开:" + socketSend.RemoteEndPoint;
                        string a = socketSend.RemoteEndPoint.ToString();
                        dicSocket[a].Close();

                        dicSocket.Remove(a);


                        break;
                    }
                    else
                    {

                    }
                }
            }
            catch (Exception e)
            {
                log.log("监听是否正常关闭的线程:" + e.Message + ",时间" + DateTime.Now);
            }
           
        }
        #region  等待客户连接 线程
        /// <summary>
        /// 等待客户端的连接,并且创建与之通信用的Socket
        /// </summary>
        /// <param name="obj"></param>
        private void StartListen(object obj)
        {
            Socket socketWatch = obj as Socket;
            while (true)
            {
                try
                {  //等待客户端的连接,并且创建一个用于通信的Socket
                    socketSend = socketWatch.Accept();
                    //获取远程主机的ip地址和端口号
                    string strIp = socketSend.RemoteEndPoint.ToString();
                    dicSocket.Add(strIp, socketSend);
                    string strMsg = "远程主机:" + socketSend.RemoteEndPoint + "连接成功"  ;
                    log.log(strMsg); //写入 Log文件里


                    //定义接收客户端消息的线程
                    threadReceive = new Thread(new ParameterizedThreadStart(Receive));
                    threadReceive.IsBackground = true;
                    threadReceive.Start(socketSend);
                    closeSocket = new Thread(new ParameterizedThreadStart(closeSocketJT)); //监听是否正常关闭
                    closeSocket.IsBackground = true;

                    closeSocket.Start(socketSend);
                }
                catch (Exception e)
                {
                    log.log("等待客户端的连接出错:" + e.Message );
                }
                         
            }
        }
        #endregion

        #region 接收消息线程
        /// <summary>
        /// 服务器端不停的接收客户端发送的消息
        /// </summary>
        /// <param name="obj"></param>
        private void Receive(object obj)
        {
          
            Socket socketSend = obj as Socket;
            int c = 0;
            string a = "";
            while (true)
            {
                //客户端连接成功后,服务器接收客户端发送的消息
               
                try
                {
                    byte[] buffer = new byte[2048];
                    if (socketSend.Poll(10, SelectMode.SelectRead))
                    {
                        string strReceiveMsg = "接收线程判断断开移除字典中的socket:" + socketSend.RemoteEndPoint;
                        string b = socketSend.RemoteEndPoint.ToString();
                        dicSocket[b].Close();
                        log.log(strReceiveMsg  );
                        dicSocket.Remove(b);
                        break;
                    }
                    else
                    {
                        int count = socketSend.Receive(buffer);
                        if (count == 0)//count 表示客户端关闭,要退出循环
                        {
                            break;
                        }
                        else
                        {
                            string str = Encoding.Default.GetString(buffer, 0, count);
                            string sixbyte = byteToHexStr(buffer, count);
                            string g = sixbyte.Substring(6, 8);
                            string cjdz = sixbyte.Substring(0, 2);
                            int b = Int32.Parse(cjdz, System.Globalization.NumberStyles.HexNumber);
                            byte[] byteArray = HexStrTobyte(g);
                            byte[] COD = new byte[4] { byteArray[1], byteArray[0], byteArray[3], byteArray[2] };

                            if (sixbyte.Length == 18)
                            {
                                c = c + b;
                                if (c == b)
                                {
                                    string strReceiveMsg2 = "接收1:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() ;
                                    log.log(strReceiveMsg2);
                                    
                                    a += b + "," + Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString();
                                    FirstOrderGasOrder(socketSend, sixbyte);


                                }
                                if (c == 2 * b)
                                {
                                 
                                    string strReceiveMsg = "接收2:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() ;
                                    log.log(strReceiveMsg);
                                    SecondOrderOrder(socketSend, sixbyte);
                                    a += "," + Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
                                 

                                }
                                if (c == 3 * b)
                                {
                                   
                                    string strReceiveMsg = "接收3:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() ;
                                    log.log(strReceiveMsg);
                                    temperatureOrder(socketSend, sixbyte);
                                    a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
                                   

                                }
                                if (c == 4 * b)
                                {

                                   
                                    string strReceiveMsg = "接收4:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() ;
                                    log.log(strReceiveMsg);
                                    humidityOrder(socketSend, sixbyte);
                                    a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
                                    

                                }
                                if (c == 5 * b)
                                {

                                    string strReceiveMsg = "接收5:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() ;
                                    a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString().ToString();
                                    SendUrl(a);
                                    log.log(strReceiveMsg);
                                    log.log(a);                                 
                                    c = 0;
                                    a = "";
                                }
                            }

                        }

                    }

                }
                catch (Exception ex)
                {
                    log.log("给客户端接收消息线程出错:" + ex.Message + ",时间" + DateTime.Now );
                 

                    break;
                }

              
            }
        }
        #endregion
        private void SendUrl(string a)
        {
            try
            {
                string[] achara = a.Split(',');


                String str = ConfigurationManager.AppSettings["IfUrl"] + "appport/GetGas" + "?FormId=" + achara[0] + "&&Oxygen=" + achara[1] + "&&Ammonia=" + achara[2] + "&&HydrogenSulfide=" + achara[3] + "&&Temperature=" + achara[4] + "&&Humidity=" + achara[5];
                string param = "";
                byte[] bs = Encoding.ASCII.GetBytes(param);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(str);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    //FileStream fs = new FileStream("c:\\easyTouch\\新建文件夹\\定时访问.txt", FileMode.Append);
                    //StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    //sw.Write("访问完成>>>>>>>>>>>>>:" + DateTime.Now);
                    //sw.Close();
                    //fs.Close();
                }
                using (WebResponse wr = req.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                }
            }
            catch (Exception ex)
            {
                log.log("向服务器接收报错:" + ex.Message + "时间" + DateTime.Now);
            }
        }
        #region 字节与16进制相互转化
        // 字节数组转16进制字符串   
        public static string byteToHexStr(byte[] bytes, int count)
        {

            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < count; i++)
                {
                    returnStr += bytes[i].ToString("X2");//ToString("X2") 为C#中的字符串格式控制符
                }
            }
            return returnStr;
        }
        // 16进制字符串转字节数组   格式为 string sendMessage = "00 01 00 00 00 06 FF 05 00 64 00 00";
        private static byte[] HexStrTobyte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
            return returnBytes;
        }
        #endregion

        #region //定时执行事件
        private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (dicSocket.Count == 0)
                { }
                else
                {
                    foreach (var item in dicSocket)
                    {
                        string cjdz = ConfigurationManager.AppSettings["MachineAddress"].Trim();
                        string[] achara = cjdz.Split(',');

                        foreach (var item2 in achara)
                        {
                            if (dicSocket[item.Key].Poll(10, SelectMode.SelectRead))
                            {
                                string strReceiveMsg = "断开:" + dicSocket[item.Key].RemoteEndPoint+"时间"+DateTime.Now ;
                                string a = dicSocket[item.Key].RemoteEndPoint.ToString();
                                dicSocket[item.Key].Close();
                                log.log(strReceiveMsg);
                                dicSocket.Remove(a);
                                break;
                            }
                            else
                            {
                                string seceond = Convert.ToInt16(item2).ToString("x2") + FourOrderGas;
                                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                                byte[] sixmsg = HexStrTobyte(Last);
                                Thread.Sleep(500);
                                dicSocket[item.Key].Send(sixmsg);
                                
                                string strReceiveMsg = "发送:" + dicSocket[item.Key].RemoteEndPoint + "发送的消息:" + Last  ;
                                log.log(strReceiveMsg);                              
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
              
                log.log("给客户端接收消息线程出错3:" + ex.Message +"时间"+DateTime.Now);
            }

      
        }
        #endregion
        #region 四种命令
        private void FirstOrderGasOrder(object obj, string a)
        {
            try
            {
                Socket socketSend = obj as Socket;
                string b = a;
                string seceond = b.Substring(0, 2) + FirstOrderGas;

                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                byte[] sixmsg = HexStrTobyte(Last);
                Thread.Sleep(1000);
                dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
                string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last  ;
                log.log(strReceiveMsg);

              
            }
            catch (Exception ex)
            {
                log.log("给客户端发送命令出错:" + ex.Message + ",时间" + DateTime.Now );
              
            }
           

        }
        private void SecondOrderOrder(object obj, string a)
        {
            try
            {
                Socket socketSend = obj as Socket;
                string b = a;
                string seceond = b.Substring(0, 2) + SecondOrderGas;

                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                byte[] sixmsg = HexStrTobyte(Last);
                Thread.Sleep(1000);
                dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
                string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last ;
                log.log(strReceiveMsg );

            }
            catch (Exception ex)
            {
                log.log("给客户端发送命令出错:" + ex.Message );
            }
          
        }
        private void temperatureOrder(object obj, string a)
        {
            try
            {
                Socket socketSend = obj as Socket;
                string b = a;
                string seceond = b.Substring(0, 2) + temperature;

                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                byte[] sixmsg = HexStrTobyte(Last);
                Thread.Sleep(1000);
                dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
                string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last ;
                log.log(strReceiveMsg );
            }
            catch (Exception ex)
            {
                log.log("给客户端发送命令出错:" + ex.Message  );
            }
           
        }
        private void humidityOrder(object obj, string a)
        {
            try
            {
                Socket socketSend = obj as Socket;
                string b = a;
                string seceond = b.Substring(0, 2) + humidity;

                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                byte[] sixmsg = HexStrTobyte(Last);
                Thread.Sleep(1000);
                dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
                string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last ;
                log.log(strReceiveMsg );
            }
            catch (Exception ex)
            {
                log.log("给客户端发送命令出错:" + ex.Message  );
            }
           

        }
        #endregion
        private void CallbackTask(Object stateInfo)
        {
            OpenM.RefundOrder();

        }
        #region Log文件
        public class Log
        {
            private string logFile;
            private StreamWriter writer;
            private FileStream fileStream = null;

            public Log(string fileName)
            {
                logFile = fileName;
                CreateDirectory(logFile);
            }

            public void log(string info)
            {

                try
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
                    if (!fileInfo.Exists)
                    {
                        fileStream = fileInfo.Create();
                        writer = new StreamWriter(fileStream);
                    }
                    else
                    {
                        fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
                        writer = new StreamWriter(fileStream);
                    }
                    writer.WriteLine(DateTime.Now + ": " + info + " \r \n");

                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer.Dispose();
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                }
            }

            public void CreateDirectory(string infoPath)
            {
                DirectoryInfo directoryInfo = Directory.GetParent(infoPath);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
            }
        }
        #endregion
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值