예제 #1
0
 /// <summary>
 /// �Ƴ���ص��豸��û��ָ���豸���Ƴ�����ָ��,�����Ч(������ʱ)ָ���Ƴ�
 /// </summary>
 /// <param name="info">ָ�����ݣ�service='halt',device(���ŷָ����豸ID),id,all='true'</param>
 /// <param name="client">�ͻ���������Ϣ</param>
 public void Haltdev(NameValueCollection info, ClientInfo client)
 {
     if (null == info)
         info = new NameValueCollection();
     string devid = info["device"];
     if (string.IsNullOrEmpty(devid))
         devid = "";
     ServiceTool.LogMessage("ֹͣѲ��(�豸)��" + devid, null, EventLogEntryType.Warning);
     //�Ƴ�ָ�����豸���,���Ƴ�ָ��,���Ƴ���Чָ��
     devid = devid.ToLower();
     DateTime dtindex = DateTime.Now.AddMonths(-5);
     DeviceBase[] devs = this.devlist.ToArray();
     for (int i = 0; i < devs.Length; i++)
     {
         string id = devs[i].DevID.ToLower();
         if (!devid.Contains(id) && devs[i].dtBeat > dtindex)
             continue;
         this.devlist.Remove(devs[i]);
         devs[i].StopGather();
         ServiceTool.LogMessage("����豸��" + devs[i].DevID, null, EventLogEntryType.Warning);
     }
     this.returnInfo(info, client, true);
 }
예제 #2
0
 public byte[] HeadBeat(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]))
         return new byte[0];
     info["success"] = "true";
     info["len"] = "0";
     return ParseInfo(info);
 }
예제 #3
0
 public byte[] ExtendSrv(ClientInfo clientinfo, byte[] context)
 {
     EventHandler<ExtendEventArgs> handle = this.ExtendHandle;
     if (null == handle)
         return context;
     ExtendEventArgs args = new ExtendEventArgs(this, clientinfo, context);
     ThreadManager.QueueUserWorkItem(delegate(object obj) { handle(this, obj as ExtendEventArgs); }, args);
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if ("false" == info["response"])
         return new byte[0];
     info["len"] = "0";
     info["success"] = "true";
     info["msg"] = "������չ�¼�";
     return ParseInfo(info);
 }
예제 #4
0
 public byte[] DelFile(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]) || string.IsNullOrEmpty(info["pathfile"]))
         return new byte[0];
     try
     {
         string pathfile = getLocalPath(info["pathfile"]);
         if (File.Exists(pathfile))
         {
             File.Delete(pathfile);
             info["msg"] = "�ļ�ɾ���ɹ�";
             info["success"] = "true";
         }
     }
     catch (Exception ex)
     {
         ExceptionManager.Publish(ex);
         info["msg"] = ex.Message.Replace("\"", "��").Replace("'", "��");
         info["success"] = "false";
     }
     info["len"] = "0";
     return ParseInfo(info);
 }
예제 #5
0
 /// <summary>
 /// ������д��ͨѶ����
 /// </summary>
 /// <param name="client">�ͻ�������</param>
 /// <param name="server">������</param>
 private void writeData(ClientInfo clientinfo, ServerBase server)
 {
     if (null == clientinfo || null == server)
         return;
     Socket client = clientinfo.Client;
     List<byte[]> responseList = clientinfo.BufferResponse;
     while (true)
     {
         //������ʱ�ر��˳�
         if (DateTime.Now - clientinfo.OPdt > server.TimeDisconn)
         {
             this.closeClientInfo(clientinfo, server);
             DisconnEventArgs args = new DisconnEventArgs(client, server);
             this.raiseEvent(args);
             return;
         }
         for (int i = 0; i < 80; i++)
         {
             if (responseList.Count > 0)
                 break;
             Thread.Sleep(5);
         }
         if (responseList.Count < 1)
             continue;
         //ͬ���¼�����������Ӧ����
         clientinfo.OPdt = DateTime.Now;
         Monitor.Enter(clientinfo);
         byte[][] responseArray = responseList.ToArray();
         responseList.Clear();
         Monitor.PulseAll(clientinfo);
         Monitor.Exit(clientinfo);
         try
         {
             for (int i = 0; i < responseArray.Length; i++)
             {
                 client.Send(responseArray[i]);
                 ResponseSrvEventArgs argresp = new ResponseSrvEventArgs(client, server, responseArray[i]);
                 this.raiseEvent(argresp);
             }
         }
         catch (Exception ex)
         {
             this.closeClientInfo(clientinfo, server);
             DisconnEventArgs args = new DisconnEventArgs(client, server, ex);
             this.raiseEvent(args);
             return;
         }
         clientinfo.OPdt = DateTime.Now;
     }
 }
예제 #6
0
        /// <summary>
        /// ��������ȡͨѶ����
        /// </summary>
        /// <param name="client">�ͻ�������</param>
        /// <param name="server">������</param>
        private void readData(ClientInfo clientinfo, ServerBase server)
        {
            if (null == clientinfo || null == server)
                return;
            Socket client = clientinfo.Client;
            bool isopen = false;
            int iM = 1048576, available = 0;
            try
            {
                isopen = client.Connected;
                available = isopen ? client.Available : 0;
            }
            catch { return; }

            List<byte[]> responseList = clientinfo.BufferResponse;
            byte[] buffer = new byte[client.ReceiveBufferSize];
            MemoryStream stream = new MemoryStream();
            byte[] b = null;
            while (true)
            {
                while (available > 0)
                {
                    try
                    {
                        //ִ������
                        byte[] request = stream.ToArray();
                        long pos = stream.Position;
                        int len = client.Receive(buffer);
                        available = client.Available;
                        clientinfo.OPdt = DateTime.Now;
                        if (request.Length > 0)
                        {
                            stream = new MemoryStream();
                            long lenr = request.LongLength;
                            for (int i = 0; i * iM < lenr; i++)
                                stream.Write(request, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
                        }
                        stream.Seek(pos, SeekOrigin.Begin);
                        byte[] reqarg = new byte[len];
                        Array.Copy(buffer, reqarg, len);
                        RequestEventArgs argreq = new RequestEventArgs(client, server, reqarg);
                        this.raiseEvent(argreq);
                        b = server.Execute(clientinfo, buffer, len, ref stream);
                    }
                    catch (Exception ex)
                    {
                        byte[] request = stream.ToArray();
                        stream = new MemoryStream();
                        ErrorRequestEventArgs argerr = new ErrorRequestEventArgs(client, server, request, ex);
                        this.raiseEvent(argerr);
                        if (ex is SocketException)
                        {
                            isopen = false;
                            break;
                        }
                        continue;
                    }
                    //��Ӧ���д�뻺��,����ͬ���¼�д����Ӧ
                    if (null != b && b.Length > 0)
                    {
                        Monitor.Enter(clientinfo);
                        responseList.Add(b);
                        Monitor.PulseAll(clientinfo);
                        Monitor.Exit(clientinfo);
                    }
                }//while (available > 0)
                while(available < 1)
                {
                    Thread.Sleep(10);
                    try
                    {
                        isopen = client.Connected;
                        available = isopen ? client.Available : 0;
                        if (!isopen) break;
                    }
                    catch
                    {
                        available = 0;
                        isopen = false;
                        break;
                    }
                }
                if (!isopen)
                {
                    this.closeClientInfo(clientinfo, server);
                    return;
                }
            }//while (true)
        }
예제 #7
0
 /// <summary>
 /// 请求事件参数构造函数
 /// </summary>
 /// <param name="server">服务器服务实例</param>
 /// <param name="client">客户端实例</param>
 /// <param name="request">请求数据内容</param>
 public ExtendEventArgs(ServerBase server, ClientInfo client, byte[] request)
 {
     Server = server;
     Client = client;
     Request = request;
     if (null != request)
         ContentLen = request.Length;
 }
 /// <summary>
 /// 移除监控的设备或没有指定设备就移除整个指令,或对无效(心跳超时)指令移除
 /// </summary>
 /// <param name="info">指令内容:service='halt',device,id,all='true'</param>
 /// <param name="client">客户端连接信息</param>
 public void Haltdev(NameValueCollection info, ClientInfo client)
 {
     if (null == info)
         info = new NameValueCollection();
     string cmdid = info["id"];
     string devid = info["device"];
     string all = info["all"];
     if (!string.IsNullOrEmpty(devid))
     {
         devid += "," + devid + ",";
         devid = devid.Replace(",,", ",");
     }
     if (!string.IsNullOrEmpty(all))
         all = all.ToLower();
     ServiceTool.LogMessage("停止巡检:" + cmdid + "\r\n设备:" + devid, null, EventLogEntryType.Warning);
     //移除指定的设备监控,或移除指令,或移除无效指令
     TimeSpan ts = new TimeSpan(0, 5, 0);
     DateTime dtNow = DateTime.Now;
     ClientMap[] maps = this.clientlist.ToArray();
     for (int i = maps.Length - 1; i > -1; i--)
     {
         if (null == maps[i] || null == maps[i].client.Client || !maps[i].client.Client.Connected)
         {
             MonitorCommand[] cmdsd = new MonitorCommand[0];
             if (null != maps[i])
                 maps[i].cmds.Clear();
             this.clientlist.Remove(maps[i]);
             ServiceTool.LogMessage("清除指令" + maps[i].client.IPEndPoint, null, EventLogEntryType.Warning);
             continue;
         }
         MonitorCommand[] cmds = maps[i].cmds.ToArray();
         for (int m = 0; m < cmds.Length; m++)
         {
             MonitorCommand cmd = cmds[m];
             if (cmdid != cmd.cmdid && dtNow - cmd.dtbeat > ts)
             {
                 maps[i].cmds.Remove(cmd);
                 continue;
             }
             if (cmdid == cmd.cmdid && string.IsNullOrEmpty(devid))
                 maps[i].cmds.Remove(cmd);
             else if ((cmdid == cmd.cmdid || "true" == all) && cmd.devices.Contains(devid))
                 cmd.devices = cmd.devices.Replace(devid, ",");
         }
         if (maps[i].cmds.Count < 1)
             this.clientlist.Remove(maps[i]);
         //移除巡检设备
         if ("true" == all && !string.IsNullOrEmpty(devid))
         {
             devid = devid.Replace(",", "");
             DeviceBase[] devices = this.devlist.ToArray();
             for (int m = 0; m < devices.Length; m++)
             {
                 if (devid != devices[m].DevID)
                     continue;
                 this.devlist.Remove(devices[m]);
                 devices[m].StopGather();
                 ServiceTool.LogMessage("清除设备:" + devices[m].DevID, null, EventLogEntryType.Warning);
                 break;
             }
         }
     }
     //不是持续巡检设备,在没有接收指令时停止巡检
     DeviceBase[] devs = this.devlist.ToArray();
     for (int i = 0; i < devs.Length; i++)
     {
         if (null == devs[i])
         {
             this.devlist.Remove(devs[i]);
             continue;
         }
         if (devs[i].IsPatrol)
             continue;
         devid = "," + devs[i].DevID + ",";
         bool isfind = false;
         maps = this.clientlist.ToArray();
         for (int m = 0; m < maps.Length; m++)
         {
             MonitorCommand[] cmds = maps[m].cmds.ToArray();
             for (int k = 0; k < cmds.Length; k++)
             {
                 if (cmds[k].devices.Contains(devid))
                     isfind = true;
                 if (isfind) break;
             }
             if (isfind) break;
         }
         if (isfind) break;
         this.devlist.Remove(devs[i]);
         devs[i].StopGather();
         ServiceTool.LogMessage("清除设备:" + devs[i].DevID, null, EventLogEntryType.Warning);
     }
     this.returnInfo(info, client, true);
 }
예제 #9
0
 /// <summary>
 /// 关闭服务的指定连接
 /// </summary>
 /// <param name="clientinfo">通讯连接</param>
 public virtual void Close(ClientInfo clientinfo)
 {
     if (null == clientinfo)
         return;
     try
     {
         clientinfo.Client.Close();
         Monitor.Enter(clientinfo);
         try
         {
             clientinfo.BufferResponse.Clear();
         }
         catch { }
         Monitor.PulseAll(clientinfo);
         Monitor.Exit(clientinfo);
     }
     catch { }
     try
     {
         Monitor.Enter(this);
         try { this.clientlist.Remove(clientinfo); }
         catch { }
         Monitor.PulseAll(this);
         Monitor.Exit(this);
     }
     catch { }
 }
예제 #10
0
 public byte[] LoadFile(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]) || string.IsNullOrEmpty(info["pathfile"]))
         return new byte[0];
     FileStream fs = null;
     try
     {
         int iM = 1048576;
         string pathfile = getLocalPath(info["pathfile"]);
         string dir = Path.GetDirectoryName(pathfile);
         if (!Directory.Exists(dir))
             Directory.CreateDirectory(dir);
         fs = File.Open(pathfile, FileMode.OpenOrCreate);
         long lenw = context.LongLength - header.Length;
         for (int i = 0; i * iM < lenw; i++)
             fs.Write(context, iM * i + header.Length, lenw > (i + 1) * iM ? iM : (int)(lenw - i * iM));
         fs.Close();
         info["msg"] = "文件保存成功";
         info["success"] = "true";
     }
     catch (Exception ex)
     {
         if (null != fs)
             fs.Close();
         ExceptionManager.Publish(ex);
         info["msg"] = ex.Message.Replace("\"", "“").Replace("'", "‘");
         info["success"] = "false";
     }
     info["len"] = "0";
     return ParseInfo(info);
 }
예제 #11
0
 /// <summary>
 /// 重载执行函数,不完整帧时接收数据缓存
 /// </summary>
 /// <param name="client">通讯连接</param>
 /// <param name="data">接收请求数据</param>
 /// <param name="bufferStream">缓存字节流</param>
 /// <returns>返回响应数据,帧不完整返回0字节,待接收完整帧执行后返回响应结果</returns>
 public override byte[] Execute(ClientInfo clientinfo, byte[] data, int len, ref MemoryStream stream)
 {
     IList<byte[]> list = new List<byte[]>();
     byte[] buffer = new byte[0];
     //没有头信息的,读入字节合并后检查头信息
     int iM = 1048576;
     if (stream.Position < 1)
     {
         buffer = new byte[stream.Length + len];
         long lenr = stream.Length;
         for (int i = 0; i * iM < lenr; i++)
             stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
         Array.Copy(data, 0, buffer, stream.Length, len);
     }
     else
     {
         //读取数据流头信息,直接读入流
         long pos = stream.Position;
         buffer = new byte[pos];
         stream.Seek(0, SeekOrigin.Begin);
         for (int i = 0; i * iM < pos; i++)
             stream.Read(buffer, iM * i, pos > (i + 1) * iM ? iM : (int)(pos - i * iM));
         NameValueCollection info = ParseInfo(buffer);
         long flen = Convert.ToInt64(info["len"]);
         stream.Seek(0, SeekOrigin.End);
         //大字节流继续读入
         if (flen > stream.Length + len - pos)
         {
             stream.Write(data, 0, len);
             stream.Seek(pos, SeekOrigin.Begin);
             return new byte[0];
         }
         long lennext = (stream.Length + len - pos - flen);
         if (lennext > len)
         {
             //上次流中已经有完整信息
             long lenr = pos + flen;
             buffer = new byte[lenr];
             stream.Seek(0, SeekOrigin.Begin);
             for (int i = 0; i * iM < lenr; i++)
                 stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
             list.Add(buffer);
             buffer = new byte[lennext];
             lenr = stream.Length - pos - flen;
             for (int i = 0; i * iM < lenr; i++)
                 stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
             Array.Copy(data, buffer, len);
         }
         else
         {
             //大字节流完整字节加入列表,后续字节继续分析头信息
             if (len > lennext)
                 stream.Write(data, 0, len - (int)lennext);
             list.Add(stream.ToArray());
             buffer = new byte[lennext];
             Array.Copy(data, len - lennext, buffer, 0, lennext);
         }
     }
     buffer = MergeResponseHdl(buffer, list);
     if (stream.Length > 0 || buffer.Length > 0)
     {
         stream = new MemoryStream(buffer);
         data = GetFileheader(buffer);
         if (null != data && data.Length > 0)
             stream.Seek(data.LongLength, SeekOrigin.Begin);
     }
     for (int i = list.Count - 1; i > -1; i--)
     {
         byte[] context = list[i];
         byte[] header = GetFileheader(context);
         NameValueCollection info = ParseInfo(header);
         RequestEventArgs args = new RequestEventArgs(null, this, context);
         int rtn = this.RaiseRequest(args);
         string keycmd = info["cmd"];
         if (string.IsNullOrEmpty(keycmd) || !this.CmdMap.ContainsKey(keycmd))
         {
             list.RemoveAt(i);
             continue;
         }
         if (rtn < 0)
             continue;
         HdlExecute hdl = this.CmdMap[info["cmd"]];
         //执行指令获取响应结果
         try
         {
             list[i] = hdl(clientinfo, context);
         }
         catch (Exception ex)
         {
             ExceptionManager.Publish(ex);
             list.RemoveAt(i);
         }
     }
     //输出响应
     if (list.Count < 1)
         return new byte[0];
     if (list.Count < 2)
         return list[0];
     //多个请求时合并输出字节
     long lend = 0;
     foreach (byte[] b in list)
         lend += b.LongLength;
     data = new byte[lend];
     lend = 0;
     foreach (byte[] b in list)
     {
         Array.Copy(b, 0, data, lend, b.LongLength);
         lend += b.LongLength;
     }
     return data;
 }
예제 #12
0
 /// <summary>
 /// 解析数据返回响应数据
 /// </summary>
 /// <param name="clientinfo">通讯连接</param>
 /// <param name="data">数据字节</param>
 /// <param name="len">字节长度</param>
 /// <param name="buffer">已接收数据缓存</param>
 /// <returns>返回执行结果</returns>
 public virtual byte[] Execute(ClientInfo clientinfo, byte[] data, int len, ref MemoryStream stream)
 {
     return(new byte[0]);
 }
예제 #13
0
 /// <summary>
 /// 监控设备,巡检指令心跳,增加巡检设备
 /// 间隔超过5分钟自动认为该指令退出
 /// </summary>
 /// <param name="info">指令内容:service='monitor',device(逗号分割多个设备ID),id,patrol='true'(patrol持续执行)</param>
 /// <param name="client">客户端连接信息</param>
 public void Monitordev(NameValueCollection info, ClientInfo client)
 {
     if (null == info || null == client || null == client.Client || !client.Client.Connected)
         return;
     string devids = info["device"];
     this.returnInfo(info, client, true);
     if (string.IsNullOrEmpty(devids))
         return;
     //加入设备列表,并增加巡检设备
     string[] devices = devids.ToLower().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
     devids = ",";
     Monitor.Enter(devlist);
     DeviceBase[] devs = devlist.ToArray();
     Monitor.PulseAll(devlist);
     Monitor.Exit(devlist);
     for (int i = 0; i < devices.Length; i++)
     {
         string id=devices[i];
         if (devids.Contains("," + id + ","))
             continue;
         bool exist = false;
         devids += id + ",";
         for (int j = 0; j < devs.Length; j++)
         {
             if (id != devs[j].DevID.ToLower())
                 continue;
             devs[j].dtBeat = DateTime.Now;
             exist = true;
             break;
         }
         if (exist) continue;
         this.addDevice(id, true);
     }
 }
예제 #14
0
 /// <summary>
 /// 移除监控的设备或没有指定设备就移除整个指令,或对无效(心跳超时)指令移除
 /// </summary>
 /// <param name="info">指令内容:service='halt',device(逗号分割多个设备ID),id,all='true'</param>
 /// <param name="client">客户端连接信息</param>
 public void Haltdev(NameValueCollection info, ClientInfo client)
 {
     if (null == info)
         info = new NameValueCollection();
     string devid = info["device"];
     if (string.IsNullOrEmpty(devid))
         devid = "";
     this.returnInfo(info, client, true);
     //移除指定的设备监控,或移除指令,或移除无效指令
     devid = devid.ToLower();
     DateTime dtindex = DateTime.Now.AddMinutes(-25);
     Monitor.Enter(devlist);
     DeviceBase[] devs = this.devlist.ToArray();
     Monitor.PulseAll(devlist);
     Monitor.Exit(devlist);
     for (int i = 0; i < devs.Length; i++)
     {
         string id = devs[i].DevID.ToLower();
         if (!devid.Contains(id) && devs[i].dtBeat > dtindex)
             continue;
         Monitor.Enter(devlist);
         this.devlist.Remove(devs[i]);
         Monitor.PulseAll(devlist);
         Monitor.Exit(devlist);
         devs[i].StopGather();
         Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 停止:" + id);
         myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 停止:" + id);
     }
 }
예제 #15
0
 /// <summary>
 /// 服务器写入通讯数据
 /// </summary>
 /// <param name="client">客户端连接</param>
 /// <param name="server">服务器</param>
 private void writeData(ClientInfo clientinfo, ServerBase server)
 {
     if (null == clientinfo || null == server)
         return;
     Socket client = clientinfo.Client;
     List<byte[]> responseList = clientinfo.BufferResponse;
     while (true)
     {
         //心跳超时关闭退出
         if (DateTime.Now - clientinfo.OPdt > server.TimeDisconn)
         {
             server.Close(clientinfo);
             //string msgex = "心跳超时退出,剩余连接数:" + Convert.ToString(server.ClientList.Count);
             //ExceptionManager.Publish(new Exception(msgex));
             DisconnEventArgs args = new DisconnEventArgs(client, server);
             this.raiseEvent(args);
             return;
         }
         for (int i = 0; i < 80; i++)
         {
             if (responseList.Count > 0)
                 break;
             Thread.Sleep(5);
         }
         if (responseList.Count < 1)
             continue;
         //同步事件触发发送响应数据
         clientinfo.OPdt = DateTime.Now;
         Monitor.Enter(clientinfo);
         byte[][] responseArray = responseList.ToArray();
         responseList.Clear();
         Monitor.PulseAll(clientinfo);
         Monitor.Exit(clientinfo);
         try
         {
             for (int i = 0; i < responseArray.Length; i++)
             {
                 client.Send(responseArray[i]);
                 Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " S发送:" + CommandBase.Parse(responseArray[i]));
                 myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " S发送:" + CommandBase.Parse(responseArray[i]));
                 ResponseSrvEventArgs argresp = new ResponseSrvEventArgs(client, server, responseArray[i]);
                 this.raiseEvent(argresp);
             }
         }
         catch (Exception ex)
         {
             server.Close(clientinfo);
             //NameValueCollection attr = new NameValueCollection();
             //attr["剩余连接数"] = Convert.ToString(server.ClientList.Count);
             //ExceptionManager.Publish(ex, attr);
             DisconnEventArgs args = new DisconnEventArgs(client, server, ex);
             this.raiseEvent(args);
             return;
         }
         clientinfo.OPdt = DateTime.Now;
     }
 }
예제 #16
0
        /// <summary>
        /// 监控设备,巡检指令心跳,增加巡检设备
        /// 间隔超过5分钟自动认为该指令退出
        /// </summary>
        /// <param name="info">指令内容:service='monitor',device,id,patrol='true'(patrol持续执行)</param>
        /// <param name="client">客户端连接信息</param>
        public void Monitordev(NameValueCollection info, ClientInfo client)
        {
            if (null == info || null == client || null == client.Client || !client.Client.Connected)
                return;
            string cmdid = info["id"];
            string devid = info["device"];
            if (string.IsNullOrEmpty(cmdid))
                return;
            ServiceTool.LogMessage("启动巡检:" + cmdid + "\r\n设备:" + devid, null, EventLogEntryType.Warning);
            //增加客户端连接信息
            ClientMap[] cms = this.clientlist.ToArray();
            ClientMap cm = null;
            for (int i = cms.Length - 1; i > -1; i--)
            {
                if (null == cms[i] || null == cms[i].client.Client || !cms[i].client.Client.Connected)
                    continue;
                if (client != cms[i].client)
                    continue;
                cm = cms[i];
                break;
            }
            if (null == cm)
            {
                cm = new ClientMap();
                cm.client = client;
                this.clientlist.Add(cm);
            }
            //添加监听指令
            MonitorCommand cmd = null;
            foreach (MonitorCommand mcd in cm.cmds)
                if (cmdid == mcd.cmdid)
                {
                    cmd = mcd;
                    break;
                }
            if (null == cmd)
            {
                cmd = new MonitorCommand();
                cmd.cmdid = cmdid;
                cm.cmds.Add(cmd);
            }
            cmd.dtbeat = DateTime.Now;

            //增加监听巡检设备
            if (string.IsNullOrEmpty(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            devid = "," + devid + ",";
            devid = devid.Replace(",,", ",");
            if (cmd.devices.Contains(devid))
            {
                this.returnInfo(info, client, true);
                return;
            }
            //加入设备列表,并增加巡检设备
            if (string.IsNullOrEmpty(cmd.devices))
                cmd.devices = devid;
            else
                cmd.devices += devid.Substring(1);
            bool ispatrol = false;
            if ("true" == info["patrol"])
                ispatrol = true;
            devid = devid.Replace(",", "");
            this.addDevice(devid, ispatrol);
            this.returnInfo(info, client, true);
        }
예제 #17
0
 /// <summary>
 /// 解析数据返回响应数据
 /// </summary>
 /// <param name="clientinfo">通讯连接</param>
 /// <param name="data">数据字节</param>
 /// <param name="len">字节长度</param>
 /// <param name="buffer">已接收数据缓存</param>
 /// <returns>返回执行结果</returns>
 public virtual byte[] Execute(ClientInfo clientinfo, byte[] data, int len, ref MemoryStream stream)
 {
     return new byte[0];
 }
예제 #18
0
 /// <summary>
 /// 反馈指令是否成功
 /// </summary>
 /// <param name="isSeccess">是否成功</param>
 private void returnInfo(NameValueCollection info, ClientInfo client, bool isSeccess)
 {
     if (null == info || null == client || null == client.Client)
         return;
     string[] keys ={ "id", "cmd", "service" };
     NameValueCollection msg = new NameValueCollection();
     foreach (string k in keys)
         msg[k] = info[k];
     msg["len"] = "0";
     msg["success"] = isSeccess ? "true" : "false";
     byte[] context = SvrFileTrans.ParseInfo(msg);
     Monitor.Enter(client);
     client.BufferResponse.Add(context);
     Monitor.PulseAll(client);
     Monitor.Exit(client);
 }
예제 #19
0
 /// <summary>
 /// 添加新的通讯连接,无连接的则暂停接收新请求
 /// </summary>
 /// <param name="client">新的通讯连接</param>
 /// <returns>返回新的客户端连接信息,暂停时返回null</returns>
 public virtual ClientInfo Add(Socket client)
 {
     ClientInfo info = new ClientInfo(client);
     Monitor.Enter(this);
     ClientInfo[] cs = this.clientlist.ToArray();
     this.clientlist.Add(info);
     Monitor.PulseAll(this);
     Monitor.Exit(this);
     //检测连接,关闭不再连接的
     foreach(ClientInfo c in cs)
     {
         try
         {
             if (c.Client.Connected || c.Client.Available > 0)
                 continue;
         }
         catch { }
         Close(c);
     }
     return info;
 }
예제 #20
0
        /// <summary>
        /// �رտͻ������Ӳ��ͷŻ�����Ϣ
        /// </summary>
        /// <param name="clientinfo"></param>
        /// <param name="server"></param>
        private void closeClientInfo(ClientInfo clientinfo, ServerBase server)
        {
            try
            {
                clientinfo.Client.Close();
                Monitor.Enter(clientinfo);
                clientinfo.BufferResponse.Clear();
                Monitor.PulseAll(clientinfo);
                Monitor.Exit(clientinfo);

                Monitor.Enter(server);
                server.ClientList.Remove(clientinfo);
                Monitor.PulseAll(server);
                Monitor.Exit(server);
            }
            catch { }
        }
예제 #21
0
 /// <summary>
 /// 读取区域信息
 /// </summary>
 /// <param name="info">指令内容:service='readregionsum',id, region='regionid'</param>
 /// <param name="client">客户端连接信息</param>
 public void ReadRegionSum(NameValueCollection info, ClientInfo client)
 {
     if (null == info)
         return;
     string cmdid = info["id"];
     string region = info["region"];
     if (string.IsNullOrEmpty(cmdid) || string.IsNullOrEmpty(region))
         return;
     Monitor.Enter(listwk);
     ChannelWorker[] wks = listwk.ToArray();
     Monitor.PulseAll(listwk);
     Monitor.Exit(listwk);
     string tag = "";
     int sum = 0;
     DateTime dtmin = DateTime.Today.AddYears(-10);
     for (int i = 0; i < wks.Length; i++)
     {
         ChannelWorker wk = wks[i];
         if (null == wk || wk.RegionID != region)
             continue;
         if (wk.DtIn < dtmin && wk.DtRein < dtmin)
             continue;
         if (wk.DtOut < dtmin && wk.DtReout < dtmin)
             sum++;
         else
         {
             DateTime dtin = wk.DtRein > wk.DtIn ? wk.DtRein : wk.DtIn;
             DateTime dtout = wk.DtReout > wk.DtOut ? wk.DtReout : wk.DtOut;
             if (dtout < dtin) sum++;
         }
     }
     DataRow[] drs = tabRegionSum.Select("ID='" + region + "'");
     if (drs.Length > 0)
         tag = basefun.setvaltag(tag, "注册人员", Convert.ToString(drs[0]["注册人员"]));
     tag = basefun.setvaltag(tag, "入内人员", Convert.ToString(sum));
     NameValueCollection nvclient = new NameValueCollection();
     string[,] map ={ { "id", cmdid }, { "cmd", "TransFile.extend" }, { "service", "readwkregion" }, { "len", "0" } };
     for (int i = 0; i < map.GetLength(0); i++)
         nvclient.Add(map[i, 0], map[i, 1]);
     byte[] data = Encoding.GetEncoding("GB2312").GetBytes(tag);
     nvclient["len"] = Convert.ToString(data.LongLength);
     byte[] context = SvrFileTrans.ParseInfo(nvclient);
     long len = context.LongLength;
     byte[] response = new byte[context.LongLength + data.LongLength];
     Array.Copy(context, response, len);
     Array.Copy(data, 0, response, len, data.LongLength);
     Monitor.Enter(client);
     client.BufferResponse.Add(response);
     Monitor.PulseAll(client);
     Monitor.Exit(client);
 }
예제 #22
0
 /// <summary>
 /// �������,�Ѿ���������,��ռ������Լ�������
 /// </summary>
 /// <param name="port">�˿ں�</param>
 /// <param name="server">������</param>
 private void start(int port, ServerBase server)
 {
     if (port < 1024 || null == server)
         return;
     if (this.listenermap.ContainsKey(port))
         return;
     server.Port = port;
     IPEndPoint localport = new IPEndPoint(IPAddress.Any, port);
     TcpListener listener = new TcpListener(localport);
     this.listenermap.Add(port, listener);
     try
     {
         listener.Start();
     }
     catch
     {
         this.listenermap.Remove(port);
         return;
     }
     while (true)
     {
         Socket client = null;
         try
         {
             client = listener.AcceptSocket();
         }
         catch (Exception ex)
         {
             ErrorRequestEventArgs args = new ErrorRequestEventArgs(client, server, new byte[0], ex);
             this.raiseEvent(args);
             if (!this.listenermap.ContainsKey(port))
                 return;
             listener.Start();
             continue;
         }
         ClientInfo info = new ClientInfo(client);
         Monitor.Enter(server);
         server.ClientList.Add(info);
         Monitor.PulseAll(server);
         Monitor.Exit(server);
         ThreadManager.QueueUserWorkItem(delegate(object obj) { this.readData(info, server); }, null);
         ThreadManager.QueueUserWorkItem(delegate(object obj) { this.writeData(info, server); }, null);
     }
 }
예제 #23
0
 /// <summary>
 /// 读取动态员工信息
 /// </summary>
 /// <param name="info">指令内容:service='readwkchannel',id, dept='deptid',dt='yyyy-MM-dd HH:mm:ss'</param>
 /// <param name="client">客户端连接信息</param>
 public void ReadWorker(NameValueCollection info, ClientInfo client)
 {
     if (null == info)
         return;
     string cmdid = info["id"];
     string dt = info["dt"];
     string dept = info["dept"];
     if (string.IsNullOrEmpty(cmdid) || string.IsNullOrEmpty(dept))
         return;
     DateTime dtindex = DateTime.MinValue;
     if (!string.IsNullOrEmpty(dt))
         try { dtindex = Convert.ToDateTime(dt); }
         catch { }
     
     Monitor.Enter(listwk);
     ChannelWorker[] wks=listwk.ToArray();
     Monitor.PulseAll(listwk);
     Monitor.Exit(listwk);
     StringBuilder sbtag = new StringBuilder();
     DateTime dtr = DateTime.MinValue;
     bool isrefreshHTML = false;
     for (int i = 0; i < wks.Length; i++)
     {
         if (null == wks[i] || wks[i].DtReceive < dtindex || wks[i].DeptID != dept)
             continue;
         if (dtr < wks[i].DtReceive)
             dtr = wks[i].DtReceive;
         try
         {
             sbtag.Append(";" + wks[i].ToTagString());
         }
         catch (Exception ex)
         {
             if (ex is OutOfMemoryException)
             {
                 isrefreshHTML = true;
                 break;
             }
         }
     }
     if(sbtag.Length>0)
     {
         try { sbtag.Remove(0, 1); }
         catch { }
         dt = dtr.ToString("yyyy-MM-dd HH:mm:ss");
     }
     NameValueCollection nvclient = new NameValueCollection();
     string[,] map ={ { "id", cmdid }, { "cmd", "TransFile.extend" }, { "service", "readwkchannel" }, { "len", "0" }, { "dt", dt } };
     for (int i = 0; i < map.GetLength(0); i++)
         nvclient.Add(map[i, 0], map[i, 1]);
     byte[] data = new byte[0];
     try
     {
         data = Encoding.GetEncoding("GB2312").GetBytes(sbtag.ToString());
     }
     catch (Exception ex)
     {
         if (ex is OutOfMemoryException)
             isrefreshHTML = true;
     }
     if (isrefreshHTML)
         nvclient["isrefreshHTML"] = "true";
     nvclient["len"] = Convert.ToString(data.LongLength);
     byte[] context = SvrFileTrans.ParseInfo(nvclient);
     long len = context.LongLength;
     byte[] response = new byte[context.LongLength + data.LongLength];
     Array.Copy(context, response, len);
     Array.Copy(data, 0, response, len, data.LongLength);
     Monitor.Enter(client);
     client.BufferResponse.Add(response);
     Monitor.PulseAll(client);
     Monitor.Exit(client);
 }
예제 #24
0
 public byte[] CommiTrans(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]) || string.IsNullOrEmpty(info["dir"])
         || string.IsNullOrEmpty(info["target"]))
         return new byte[0];
     string ipaddr = info["target"];
     if ("response" == info["dir"])
         ipaddr = info["source"];
     else
     {
         info["source"] = clientinfo.IPEndPoint.Substring(0, clientinfo.IPEndPoint.IndexOf(":"));
         byte[] hf = ParseInfo(info);
         byte[] data = new byte[hf.Length + context.Length - header.Length];
         Array.Copy(hf, data, hf.Length);
         Array.Copy(context, header.Length, data, hf.Length, context.Length - header.Length);
         context = data;
     }
     //����ͻ���������Ϣ����Ӧ�б���
     Monitor.Enter(this);
     ClientInfo[] clients = this.ClientList.ToArray();
     Monitor.PulseAll(this);
     Monitor.Exit(this);
     foreach (ClientInfo cf in clients)
         if (cf.IPEndPoint.StartsWith(ipaddr + ":"))
         {
             Monitor.Enter(cf);
             cf.BufferResponse.Add(context);
             Monitor.PulseAll(cf);
             Monitor.Exit(cf);
         }
     return new byte[0];
 }
예제 #25
0
        /// <summary>
        /// 重载执行函数,不完整帧时接收数据缓存
        /// </summary>
        /// <param name="client">通讯连接</param>
        /// <param name="data">接收请求数据</param>
        /// <param name="bufferStream">缓存字节流</param>
        /// <returns>返回响应数据,帧不完整返回0字节,待接收完整帧执行后返回响应结果</returns>
        public override byte[] Execute(ClientInfo clientinfo, byte[] data, int len, ref MemoryStream stream)
        {
            IList <byte[]> list = new List <byte[]>();

            byte[] buffer = new byte[0];
            //没有头信息的,读入字节合并后检查头信息
            int iM = 1048576;

            if (stream.Position < 1)
            {
                buffer = new byte[stream.Length + len];
                long lenr = stream.Length;
                for (int i = 0; i *iM < lenr; i++)
                {
                    stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
                }
                Array.Copy(data, 0, buffer, stream.Length, len);
            }
            else
            {
                //读取数据流头信息,直接读入流
                long pos = stream.Position;
                buffer = new byte[pos];
                stream.Seek(0, SeekOrigin.Begin);
                for (int i = 0; i *iM < pos; i++)
                {
                    stream.Read(buffer, iM * i, pos > (i + 1) * iM ? iM : (int)(pos - i * iM));
                }
                NameValueCollection info = ParseInfo(buffer);
                long flen = Convert.ToInt64(info["len"]);
                stream.Seek(0, SeekOrigin.End);
                //大字节流继续读入
                if (flen > stream.Length + len - pos)
                {
                    stream.Write(data, 0, len);
                    stream.Seek(pos, SeekOrigin.Begin);
                    return(new byte[0]);
                }
                long lennext = (stream.Length + len - pos - flen);
                if (lennext > len)
                {
                    //上次流中已经有完整信息
                    long lenr = pos + flen;
                    buffer = new byte[lenr];
                    stream.Seek(0, SeekOrigin.Begin);
                    for (int i = 0; i *iM < lenr; i++)
                    {
                        stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
                    }
                    list.Add(buffer);
                    buffer = new byte[lennext];
                    lenr   = stream.Length - pos - flen;
                    for (int i = 0; i *iM < lenr; i++)
                    {
                        stream.Read(buffer, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
                    }
                    Array.Copy(data, buffer, len);
                }
                else
                {
                    //大字节流完整字节加入列表,后续字节继续分析头信息
                    if (len > lennext)
                    {
                        stream.Write(data, 0, len - (int)lennext);
                    }
                    list.Add(stream.ToArray());
                    buffer = new byte[lennext];
                    Array.Copy(data, len - lennext, buffer, 0, lennext);
                }
            }
            buffer = MergeResponseHdl(buffer, list);
            if (stream.Length > 0 || buffer.Length > 0)
            {
                stream = new MemoryStream(buffer);
                data   = GetFileheader(buffer);
                if (null != data && data.Length > 0)
                {
                    stream.Seek(data.LongLength, SeekOrigin.Begin);
                }
            }
            for (int i = list.Count - 1; i > -1; i--)
            {
                byte[] context           = list[i];
                byte[] header            = GetFileheader(context);
                NameValueCollection info = ParseInfo(header);
                RequestEventArgs    args = new RequestEventArgs(null, this, context);
                int    rtn    = this.RaiseRequest(args);
                string keycmd = info["cmd"];
                if (string.IsNullOrEmpty(keycmd) || !this.CmdMap.ContainsKey(keycmd))
                {
                    list.RemoveAt(i);
                    continue;
                }
                if (rtn < 0)
                {
                    continue;
                }
                HdlExecute hdl = this.CmdMap[info["cmd"]];
                //执行指令获取响应结果
                try
                {
                    list[i] = hdl(clientinfo, context);
                }
                catch (Exception ex)
                {
                    ExceptionManager.Publish(ex);
                    list.RemoveAt(i);
                }
            }
            //输出响应
            if (list.Count < 1)
            {
                return(new byte[0]);
            }
            if (list.Count < 2)
            {
                return(list[0]);
            }
            //多个请求时合并输出字节
            long lend = 0;

            foreach (byte[] b in list)
            {
                lend += b.LongLength;
            }
            data = new byte[lend];
            lend = 0;
            foreach (byte[] b in list)
            {
                Array.Copy(b, 0, data, lend, b.LongLength);
                lend += b.LongLength;
            }
            return(data);
        }
예제 #26
0
 /// <summary>
 /// ����ִ�к���,������֡ʱ�������ݻ���
 /// </summary>
 /// <param name="client">ͨѶ����</param>
 /// <param name="data">������������</param>
 /// <param name="bufferStream">�����ֽ���</param>
 /// <returns>������Ӧ����,֡����������0�ֽ�,����������ִ֡�к󷵻���Ӧ���</returns>
 public override byte[] Execute(ClientInfo clientinfo, byte[] data, int len, ref MemoryStream stream)
 {
     IList<byte[]> list = new List<byte[]>();
     byte[] buffer = new byte[0];
     //û��ͷ��Ϣ�ģ������ֽںϲ�����ͷ��Ϣ
     if (stream.Position < 1)
     {
         buffer = new byte[stream.Length + len];
         stream.Read(buffer, 0, (int)stream.Length);
         Array.Copy(data, 0, buffer, stream.Length, len);
     }
     else
     {
         //��ȡ������ͷ��Ϣ,ֱ�Ӷ�����
         int pos = (int)stream.Position;
         buffer = new byte[pos];
         stream.Seek(0, SeekOrigin.Begin);
         stream.Read(buffer, 0, pos);
         NameValueCollection info = ParseInfo(buffer);
         long flen = Convert.ToInt64(info["len"]);
         stream.Seek(0, SeekOrigin.End);
         //���ֽ�����������
         if (flen > stream.Length + len - pos)
         {
             stream.Write(data, 0, len);
             stream.Seek(pos, SeekOrigin.Begin);
             return new byte[0];
         }
         int lennext = (int)(stream.Length + len - pos - flen);
         if (lennext > len)
         {
             //�ϴ������Ѿ���������Ϣ
             buffer = new byte[pos + flen];
             stream.Seek(0, SeekOrigin.Begin);
             stream.Read(buffer, 0, buffer.Length);
             list.Add(buffer);
             buffer = new byte[lennext];
             stream.Read(buffer, 0, (int)stream.Length - pos - (int)flen);
             Array.Copy(data, buffer, len);
         }
         else
         {
             //���ֽ��������ֽڼ����б�,�����ֽڼ�������ͷ��Ϣ
             if (len > lennext)
                 stream.Write(data, 0, len - lennext);
             list.Add(stream.ToArray());
             buffer = new byte[lennext];
             Array.Copy(data, len - lennext, buffer, 0, lennext);
         }
     }
     buffer = MergeResponseHdl(buffer, list);
     if (stream.Length > 0 || buffer.Length > 0)
     {
         stream = new MemoryStream(buffer);
         data = GetFileheader(buffer);
         if (null != data && data.Length > 0)
             stream.Seek(data.Length, SeekOrigin.Begin);
     }
     for (int i = list.Count - 1; i > -1; i--)
     {
         byte[] context = list[i];
         byte[] header = GetFileheader(context);
         NameValueCollection info = ParseInfo(header);
         RequestEventArgs args = new RequestEventArgs(null, this, context);
         int rtn = this.RaiseRequest(args);
         string keycmd = info["cmd"];
         if (string.IsNullOrEmpty(keycmd) || !this.CmdMap.ContainsKey(keycmd))
         {
             list.RemoveAt(i);
             continue;
         }
         if (rtn < 0)
             continue;
         HdlExecute hdl = this.CmdMap[info["cmd"]];
         //ִ��ָ���ȡ��Ӧ���
         try
         {
             list[i] = hdl(clientinfo, context);
         }
         catch (Exception ex)
         {
             ExceptionManager.Publish(ex);
             list.RemoveAt(i);
         }
     }
     //�����Ӧ
     if (list.Count < 1)
         return new byte[0];
     if (list.Count < 2)
         return list[0];
     //�������ʱ�ϲ�����ֽ�
     long lend = 0;
     foreach (byte[] b in list)
         lend += b.LongLength;
     data = new byte[lend];
     lend = 0;
     foreach (byte[] b in list)
     {
         Array.Copy(b, 0, data, lend, b.LongLength);
         lend += b.LongLength;
     }
     return data;
 }
예제 #27
0
 /// <summary>
 /// ����豸,Ѳ��ָ������,����Ѳ���豸
 /// ������5�����Զ���Ϊ��ָ���˳�
 /// </summary>
 /// <param name="info">ָ�����ݣ�service='monitor',device(���ŷָ����豸ID),id,patrol='true'(patrol����ִ��)</param>
 /// <param name="client">�ͻ���������Ϣ</param>
 public void Monitordev(NameValueCollection info, ClientInfo client)
 {
     if (null == info || null == client || null == client.Client || !client.Client.Connected)
         return;
     string devid = info["device"];
     if (string.IsNullOrEmpty(devid))
     {
         this.returnInfo(info, client, true);
         return;
     }
     ServiceTool.LogMessage("���Ѳ��(�豸)��" + devid, null, EventLogEntryType.Warning);
     //�����豸�б�,������Ѳ���豸
     string[] devices = devid.ToLower().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
     DeviceBase[] devs = devlist.ToArray();
     for (int i = 0; i < devices.Length; i++)
     {
         string id=devices[i];
         bool exist = false;
         for (int j = 0; j < devs.Length; j++)
         {
             if (id != devs[i].DevID.ToLower())
                 continue;
             devs[j].dtBeat = DateTime.Now;
             exist = true;
             break;
         }
         if (exist) continue;
         this.addDevice(devid, true);
     }
     this.returnInfo(info, client, true);
 }
예제 #28
0
 public byte[] GetFile(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]) || string.IsNullOrEmpty(info["pathfile"]))
         return new byte[0];
     context = new byte[0];
     try
     {
         string pathfile = getLocalPath(info["pathfile"]);
         if (!File.Exists(pathfile))
         {
             info["msg"] = "�ļ�������";
             info["success"] = "false";
         }
         else
         {
             context = File.ReadAllBytes(pathfile);
             info["msg"] = "�ļ���ȡ�ɹ�";
             info["success"] = "true";
         }
     }
     catch (Exception ex)
     {
         context = new byte[0];
         ExceptionManager.Publish(ex);
         info["msg"] = ex.Message.Replace("\"", "��").Replace("'", "��");
         info["success"] = "false";
     }
     info["len"] = Convert.ToString(context.LongLength);
     byte[] response = ParseInfo(info);
     if (context.Length > 1)
     {
         long len=response.Length;
         Array.Resize<byte>(ref response, (int)(len + context.LongLength));
         Array.Copy(context, 0, response, len, context.LongLength);
     }
     return response;
 }
예제 #29
0
        /// <summary>
        /// ��ȡ�豸��Ϣ,���������ݺ�״̬
        /// </summary>
        /// <param name="info">ָ�����ݣ�service='halt',device,id, dt='yyyy-MM-dd HH:mm:ss',datatype='record|alarm|signal'</param>
        /// <param name="client">�ͻ���������Ϣ</param>
        public void ReadInfodev(NameValueCollection info, ClientInfo client)
        {
            if (null == info)
                return;

            string cmdid = info["id"];
            string devid = info["device"];
            string datatype = info["datatype"];
            string dt = info["dt"];
            if (string.IsNullOrEmpty(devid))
                return;
            if ("record" != datatype && "signal" != datatype && "alarm" != datatype)
                return;
            devid = devid.ToLower();
            DateTime dtindex = DateTime.Now.AddSeconds(-30);
            if (!string.IsNullOrEmpty(dt))
                try { dtindex = Convert.ToDateTime(dt); }
                catch { }

            //���dz���Ѳ���豸,���Ѳ��
            DeviceBase[] devs = this.devlist.ToArray();
            DeviceBase device = null;
            for (int i = 0; i < devs.Length; i++)
            {
                if (devid != devs[i].DevID.ToLower())
                    continue;
                device = devs[i];
                break;
            }
            if (null == device)
            {
                device = this.addDevice(devid, true);
                if (null == device)
                    return;
                Thread.Sleep(800);
            }

            //��ȡ����
            string tag = "";
            if ("alarm" == datatype)
            {
                tag = device.Alarm.tag;
                dt = device.Alarm.dtReceive.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if ("signal" == datatype)
            {
                tag = device.Signal.tag;
                dt = device.Signal.dtReceive.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if ("record" == datatype)
            {
                RecordDev[] rds = device.Rows.ToArray();
                for (int i = 0; i < rds.Length; i++)
                {
                    if (rds[i].dtReceive < dtindex)
                        continue;
                    tag += ";" + rds[i].tag;
                    dt = rds[i].dtReceive.ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!string.IsNullOrEmpty(tag))
                    tag = tag.Substring(1);
            }
            NameValueCollection nvclient = new NameValueCollection();
            string[,] map ={ { "id", cmdid }, { "cmd", "TransFile.extend" }, { "service", "readinfo" }, { "len", "0" }, { "deviceid", device.DevID }, { "datatype", datatype }, { "dt", dt } };
            for (int i = 0; i < map.GetLength(0); i++)
                nvclient.Add(map[i, 0], map[i, 1]);
            byte[] data = Encoding.GetEncoding("GB2312").GetBytes(tag);
            nvclient["len"] = Convert.ToString(data.Length);
            byte[] context = SvrFileTrans.ParseInfo(nvclient);
            int len = context.Length;
            Array.Resize<byte>(ref context, context.Length + data.Length);
            Array.Copy(data, 0, context, len, data.Length);
            Monitor.Enter(client);
            client.BufferResponse.Add(context);
            Monitor.PulseAll(client);
            Monitor.Exit(client);
        }
예제 #30
0
 public byte[] LoadFile(ClientInfo clientinfo, byte[] context)
 {
     byte[] header = GetFileheader(context);
     NameValueCollection info = ParseInfo(header);
     if (string.IsNullOrEmpty(info["id"]) || string.IsNullOrEmpty(info["pathfile"]))
         return new byte[0];
     FileStream fs = null;
     try
     {
         string pathfile = getLocalPath(info["pathfile"]);
         string dir = Path.GetDirectoryName(pathfile);
         if (!Directory.Exists(dir))
             Directory.CreateDirectory(dir);
         fs = File.Open(pathfile, FileMode.OpenOrCreate);
         fs.Write(context, header.Length, context.Length - header.Length);
         fs.Close();
         info["msg"] = "�ļ�����ɹ�";
         info["success"] = "true";
     }
     catch (Exception ex)
     {
         if (null != fs)
             fs.Close();
         ExceptionManager.Publish(ex);
         info["msg"] = ex.Message.Replace("\"", "��").Replace("'", "��");
         info["success"] = "false";
     }
     info["len"] = "0";
     return ParseInfo(info);
 }
예제 #31
0
        /// <summary>
        /// 服务器读取通讯数据
        /// </summary>
        /// <param name="client">客户端连接</param>
        /// <param name="server">服务器</param>
        private void readData(ClientInfo clientinfo, ServerBase server)
        {
            if (null == clientinfo || null == server)
                return;
            Socket client = clientinfo.Client;
            bool isopen = false;
            int iM = 1048576, available = 0;
            try
            {
                isopen = client.Connected;
                available = isopen ? client.Available : 0;
            }
            catch { return; }

            List<byte[]> responseList = clientinfo.BufferResponse;
            byte[] buffer = new byte[client.ReceiveBufferSize];
            MemoryStream stream = new MemoryStream();
            byte[] b = null;
            while (true)
            {
                while (available > 0)
                {
                    try
                    {
                        //执行请求
                        byte[] request = stream.ToArray();
                        long pos = stream.Position;
                        int len = client.Receive(buffer);
                        string msgrp = Encoding.GetEncoding("GB2312").GetString(buffer, 0, len);
                        Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " S接收:" + msgrp);
                        myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " S接收:" + msgrp);
                        clientinfo.OPdt = DateTime.Now;
                        if (request.Length > 0)
                        {
                            stream = new MemoryStream();
                            long lenr = request.LongLength;
                            for (int i = 0; i * iM < lenr; i++)
                                stream.Write(request, iM * i, lenr > (i + 1) * iM ? iM : (int)(lenr - i * iM));
                        }
                        stream.Seek(pos, SeekOrigin.Begin);
                        byte[] reqarg = new byte[len];
                        Array.Copy(buffer, reqarg, len);
                        RequestEventArgs argreq = new RequestEventArgs(client, server, reqarg);
                        this.raiseEvent(argreq);
                        b = server.Execute(clientinfo, buffer, len, ref stream);
                        available = client.Available;
                    }
                    catch (Exception ex)
                    {
                        byte[] request = stream.ToArray();
                        stream = new MemoryStream();
                        //NameValueCollection attr = new NameValueCollection();
                        //attr["剩余连接数"] = Convert.ToString(server.ClientList.Count);
                        //ExceptionManager.Publish(ex, attr);
                        ErrorRequestEventArgs argerr = new ErrorRequestEventArgs(client, server, request, ex);
                        this.raiseEvent(argerr);
                        if (ex is SocketException)
                        {
                            isopen = false;
                            break;
                        }
                        try { available = 0; isopen = client.Connected; available = isopen ? client.Available : 0; }
                        catch { isopen = false; }
                        continue;
                    }
                    //响应结果写入缓存,触发同步事件写入响应
                    if (null != b && b.Length > 0)
                    {
                        Monitor.Enter(clientinfo);
                        responseList.Add(b);
                        Monitor.PulseAll(clientinfo);
                        Monitor.Exit(clientinfo);
                    }
                }//while (available > 0)
                while(available < 1)
                {
                    Thread.Sleep(10);
                    try
                    {
                        isopen = client.Connected;
                        available = isopen ? client.Available : 0;
                        if (!isopen) break;
                    }
                    catch
                    {
                        available = 0; 
                        isopen = false; 
                        break;
                    }
                }
                if (!isopen)
                {
                    server.Close(clientinfo);
                    return;
                }
            }//while (true)
        }