Exemplo n.º 1
0
        public void UnregisterPlugin(string plugin_name)
        {
            try
            {
                CommonPair <IPlugin, List <Constants.TK_CommandType> > cmds = null;
                lock (m_Plugins)
                {
                    if (!m_Plugins.ContainsKey(plugin_name))
                    {
                        return;
                    }

                    cmds = m_Plugins[plugin_name];
                    m_Plugins.Remove(plugin_name);

                    try
                    {
                        cmds.First.Kill();
                    }
                    catch { }
                }

                foreach (Constants.TK_CommandType cmd in cmds.Second)
                {
                    CommandProcessor.instance().unregisterReportHandler(cmd, this);
                }

                Logger.Instance().SendLog("已卸载: " + plugin_name);
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog(ex.ToString());
            }
        }
Exemplo n.º 2
0
 public void UnregisterCommand()
 {
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.MON_GET_TABLUARINFO, this);
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.MON_COMMIT_TABLUARINFO, this);
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.MON_GET_TABLUARINFO_RAWQUERY, this);
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.MON_EXECUTE_NONQUERY, this);
 }
Exemplo n.º 3
0
        public bool Close()
        {
            lock (this)
            {
                if (Interlocked.Exchange(ref m_Run, 0) == 0)
                {
                    return(true);
                }

                //m_Listener.Shutdown(SocketShutdown.Both);
                m_Listener.Close();

                m_AccepterStopEvent.WaitOne();

                this.m_TimerKeepAlive.Stop();

                // 取消所有响应包的等待
                lock (this.m_MessagesWaitForResponse)
                {
                    foreach (KeyValuePair <long, CommonPair <ICommunicationMessage, ManualResetEvent> > de in this.m_MessagesWaitForResponse)
                    {
                        CommonPair <ICommunicationMessage, ManualResetEvent> elem = de.Value;
                        ManualResetEvent mutex = elem.Second;
                        mutex.Set();
                    }

                    m_MessagesWaitForResponse.Clear();
                }

                m_KeepAliveClearEvent.WaitOne();

                m_TimerCheckBroken.Stop();
                m_CheckBrokenClearEvent.WaitOne();



                lock (m_ClientCommunicators)
                {
                    foreach (Communicator comm in m_ClientCommunicators.Values)
                    {
                        comm.endWork();
                    }

                    m_ClientCommunicators.Clear();
                }

                lock (m_ClientActiveCounter)
                    m_ClientActiveCounter.Clear();

                foreach (KeyValuePair <Constants.TK_CommandType, byte> pair in m_AcceptedMsgs)
                {
                    CommandProcessor.instance().unregisterReportHandler(pair.Key, this);
                }

                //CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.RESPONSE, this);
            }

            return(true);
        }
Exemplo n.º 4
0
 /// <summary>
 /// 派发消息并分配流水号
 /// </summary>
 /// <param name="msg"></param>
 public void DispatchCommand(ICommunicationMessage msg)
 {
     if (msg.SeqID == 0)
     {
         msg.SeqID = CommandProcessor.AllocateID();
     }
     CommandProcessor.instance().DispatchCommand(msg);
 }
Exemplo n.º 5
0
        private CommandMsgV2 UserLogout(ICommunicationMessage message)
        {
            CommandMsgV2 responseMsg = new CommandMsgV2();

            try
            {
                if (message.Contains("ClientID"))
                {
                    if (message.Contains("用户名"))
                    {
                        string sUserName = message.GetValue("用户名").ToString().Trim();
                        string sql       = "update Operator set lastlogouttime = '" + DateTime.Now.ToString().Trim() + "' where login_name = '" + sUserName + "'";
                        SqlHelper.ExecuteNonQuery(m_ConnStr, CommandType.Text, sql);

                        // 注销内部客户端的数据
                        CommandMsgV2 logout = new CommandMsgV2();
                        logout.TK_CommandType = Constants.TK_CommandType.UNREGISTERCLIENT;
                        logout.SeqID          = CommandProcessor.AllocateID();
                        logout.SetValue("ClientID", message.GetValue("ClientID"));
                        CommandProcessor.instance().DispatchCommand(logout);

                        responseMsg.SeqID          = CommandProcessor.AllocateID();
                        responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                        responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                        responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                        responseMsg.SetValue("RESULT", "OK");
                    }
                    else
                    {
                        responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                        responseMsg.SeqID          = CommandProcessor.AllocateID();
                        responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                        responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                        responseMsg.SetValue("RESULT", "NOK");
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                try
                {
                    responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                    responseMsg.SeqID          = CommandProcessor.AllocateID();
                    responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                    responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                    responseMsg.SetValue("RESULT", "NOK");
                }
                catch { }
            }
            finally
            {
            }
            return(responseMsg);
        }
Exemplo n.º 6
0
        public UNAlarmServer()
        {
            Logger.Instance().SubscibeLog("", new Logger.LogFunction(Main_LogReceived));

            Timer_Log.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Log_ElapsedEvent);
            Timer_Log.Interval = 5000;

            Dictionary <Constants.TK_CommandType, byte> empty = new Dictionary <Constants.TK_CommandType, byte>();

            CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.SERVER_GETRUNTIMEINFO, this, empty);
            CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.SERVER_GETCURLOG, this, empty);
            CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.SERVER_GETLOGFILES, this, empty);
            CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.MON_GETTERMINALSINFO, this, empty);
        }
Exemplo n.º 7
0
 public void UNAlarmServer_Init()
 {
     try
     {
         Timer_Log.Start();
         //Utilities.ReadNorthServerConf();
         CommandProcessor.instance().Start(true); // as server
         AlarmManager.instance().Prepare();
         Utilities.ReadAlarmConf();
         Run();
     }
     catch (Exception ex)
     {
         receiveLog("初始化告警管理服务时发生异常: " + ex.ToString());
     }
 }
Exemplo n.º 8
0
        public bool Start()
        {
            lock (this)
            {
                try
                {
                    if (Interlocked.Exchange(ref m_Run, 1) == 1)
                    {
                        return(true);
                    }

                    m_Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//(IPAddress.Any, m_Port);
                    m_Listener.Bind(new IPEndPoint(IPAddress.Any, m_Port));
                    m_Listener.Listen(100);
                    //m_Listener.Start();

                    //Thread thr = new Thread(new ThreadStart(_accepter));
                    //thr.Start();

                    SendLog(Name + " started at " + m_Listener.LocalEndPoint.ToString());

                    foreach (KeyValuePair <Constants.TK_CommandType, byte> pair in m_AcceptedMsgs)
                    {
                        CommandProcessor.instance().registerReportHandler(pair.Key, this, m_SuperCmds);
                    }

                    if (m_bKeepAlive)
                    {
                        m_TimerKeepAlive.Start();
                    }

                    m_TimerCheckBroken.Start();

                    _asyncAccepter();
                    //CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.RESPONSE, this, new Dictionary<Constants.TK_CommandType, byte>());

                    SendLog(Name + (m_bCompress ? "(压缩)" : "") + "已启动,最大客户端数量:" + m_MaxClients);
                }
                catch (Exception ex)
                {
                    Interlocked.Exchange(ref m_Run, 0);
                    throw ex;
                }
            }

            return(true);
        }
Exemplo n.º 9
0
        public void Stop()
        {
            lock (m_LockRun)
            {
                if (Interlocked.Read(ref bRun) == 1)
                {
                    Interlocked.Exchange(ref bRun, 0);
                }
                else
                {
                    return;
                }

                CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.LOGIN, this);
                CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.LOGOUT, this);
            }
        }
Exemplo n.º 10
0
        public void RegisterPlugin(string plugin_name, string url, List <Constants.TK_CommandType> handlingcmds)
        {
            try
            {
                lock (m_Plugins)
                {
                    if (m_Plugins.ContainsKey(plugin_name))
                    {
                        UnregisterPlugin(plugin_name);
                    }
                }

                IPlugin plugin = (IPlugin)Activator.GetObject(typeof(IPlugin), url);

                lock (m_Handlers)
                {
                    foreach (Constants.TK_CommandType cmd in handlingcmds)
                    {
                        CommandProcessor.instance().registerReportHandler(cmd, this, null);

                        List <IPlugin> plugins;
                        if (m_Handlers.ContainsKey(cmd))
                        {
                            plugins = m_Handlers[cmd];
                        }
                        else
                        {
                            plugins = (m_Handlers[cmd] = new List <IPlugin>());
                        }

                        plugins.Add(plugin);
                    }
                }

                lock (m_Plugins)
                {
                    m_Plugins.Add(plugin_name, new CommonPair <IPlugin, List <Constants.TK_CommandType> >(plugin, handlingcmds));
                }

                Logger.Instance().SendLog("已安装: " + plugin_name);
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog(ex.ToString());
            }
        }
Exemplo n.º 11
0
        public void Prepare()
        {
            try
            {
                Logger.Instance().SendLog("AdapterController", "正在初始化参数...");
                Init();

                CommandProcessor.instance().Start(true);
                m_ControllerServer.Start();//通讯服务器启动

                Logger.Instance().SendLog("AdapterController", "初始化完毕.");
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog("AdapterController", ex.ToString());
            }
        }
Exemplo n.º 12
0
        public void Start()
        {
            lock (m_LockRun)
            {
                if (Interlocked.Read(ref bRun) == 1)
                {
                    return;
                }
                else
                {
                    Interlocked.Exchange(ref bRun, 1);
                }

                Dictionary <Constants.TK_CommandType, byte> super_commands = new Dictionary <Constants.TK_CommandType, byte>();
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.LOGIN, this, super_commands);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.LOGOUT, this, super_commands);
            }
        }
        void _VerifyTerminalsStatus(ICommunicationMessage message)
        {
            C5.HashDictionary <long, AdapterInfo> ads = new C5.HashDictionary <long, AdapterInfo>();
            AlarmManager.instance().GetAdaptersInfo(ads);

            foreach (C5.KeyValuePair <long, AdapterInfo> info in ads)
            {
                try
                {
                    System.Net.IPEndPoint end = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(info.Value.Address), info.Value.ControllerPort);
                    if (end.Port == 0)
                    {
                        continue;
                    }
                    else
                    {
                        ICommClient comm = CommManager.instance().CreateCommClient <CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>("控制器",
                                                                                                                                            end.Address.ToString(), end.Port, 30, false, false);

                        if (!comm.Start())
                        {
                            // remove adapter
                            AlarmManager.instance().RemoveAdapterInfo(info.Key);
                        }
                        else
                        {
                            comm.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    DefLib.Util.Logger.Instance().SendLog(ex.ToString());
                }
            }

            CommandMsgV2 msg = new CommandMsgV2();

            msg.TK_CommandType = Constants.TK_CommandType.MON_GETTERMINALSINFO;
            msg.SeqID          = message.SeqID;
            msg.SetValue("ClientID", message.GetValue("ClientID"));

            CommandProcessor.instance().DispatchCommand(msg);
        }
        public void handleCommand(ICommunicationMessage message)
        {
            switch (message.TK_CommandType)
            {
            case Constants.TK_CommandType.ADAPTER_START:
                CommandProcessor.instance().DispatchCommand(_StartAdapter(message));
                break;

            case Constants.TK_CommandType.ADAPTER_STOP:
                CommandProcessor.instance().DispatchCommand(_StopAdapter(message));
                break;

            case Constants.TK_CommandType.MON_VERIFYTERMINALSSTATUS:
                _VerifyTerminalsStatus(message);
                break;

            default:
                break;
            }
        }
Exemplo n.º 15
0
        public void handleCommand(ICommunicationMessage message)
        {
            CommandMsgV2 responseMsg = null;

            switch (message.TK_CommandType)
            {
            case Constants.TK_CommandType.LOGIN:
                responseMsg = UserLogin(message);
                break;

            case Constants.TK_CommandType.LOGOUT:
                responseMsg = UserLogout(message);
                break;

            default:
                break;
            }

            CommandProcessor.instance().DispatchCommand(responseMsg);
        }
Exemplo n.º 16
0
        public void handleCommand(ICommunicationMessage message)
        {
            switch (message.TK_CommandType)
            {
            case Constants.TK_CommandType.MON_GET_TABLUARINFO:
                CommandProcessor.instance().DispatchCommand(_GetTabluarInfo(message));
                break;

            case Constants.TK_CommandType.MON_COMMIT_TABLUARINFO:
                CommandProcessor.instance().DispatchCommand(_CommitTabluarInfo(message));
                break;

            case Constants.TK_CommandType.MON_GET_TABLUARINFO_RAWQUERY:
                CommandProcessor.instance().DispatchCommand(_GetTabluarVariantInfo(message));
                break;

            case Constants.TK_CommandType.MON_EXECUTE_NONQUERY:
                CommandProcessor.instance().DispatchCommand(_ExecuteNonQuery(message));
                break;
            }
        }
 public void UnregisterCommand()
 {
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.ADAPTER_START, this);
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.ADAPTER_STOP, this);
     CommandProcessor.instance().unregisterReportHandler(Constants.TK_CommandType.MON_VERIFYTERMINALSSTATUS, this);
 }
Exemplo n.º 18
0
        void m_TimerCheckBroken_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                m_CheckBrokenClearEvent.Reset();

                if (Interlocked.Read(ref m_Run) == 0)
                {
                    return;
                }

                if (!m_TimerCheckBroken.Enabled)
                {
                    return;
                }

                lock (m_LockCheckBroken)
                {
                    if (m_bInCheckBroken)
                    {
                        return;
                    }
                    else
                    {
                        m_bInCheckBroken = true;
                    }
                }


                List <BrokenInfo> temp = null;
                lock (m_BrokenClient)
                {
                    if (m_BrokenClient.Count > 0)
                    {
                        temp           = m_BrokenClient;
                        m_BrokenClient = new List <BrokenInfo>();
                    }
                }

                if (temp == null)
                {
                    return;
                }

                int live_count = 0;
                foreach (BrokenInfo info in temp)
                {
                    bool          isclient = false;
                    ICommunicator client   = null;
                    lock (m_ClientCommunicators)
                    {
                        isclient = m_ClientCommunicators.TryGetValue(info.Commer.ClientID, out client);
                        if (isclient)
                        {
                            m_ClientCommunicators.Remove(info.Commer.ClientID);
                        }
                        live_count = m_ClientCommunicators.Count;
                    }

                    lock (m_ClientActiveCounter)
                        m_ClientActiveCounter.Remove(info.Commer.ClientID);

                    if (isclient)
                    {
                        MSGTYPE command = new MSGTYPE();
                        command.TK_CommandType = Constants.TK_CommandType.UNREGISTERCLIENT;
                        command.SetValue("ClientID", info.Commer.ClientID);
                        command.SeqID = CommandProcessor.AllocateID();
                        CommandProcessor.instance().DispatchCommand(command);

                        SendLog("客户端: " + info.Info + " 已经从" + Name + "断开.");
                    }

                    InvokeConnectionBroken(info.Commer, info.Info);
                }

                SendLog(Name + "当前客户端的数量:" + live_count);
            }
            catch (Exception ex)
            {
                SendLog(ex.ToString());
            }
            finally
            {
                m_bInCheckBroken = false;

                m_CheckBrokenClearEvent.Set();
            }
        }
Exemplo n.º 19
0
        private CommandMsgV2 UserLogin(ICommunicationMessage message)
        {
            CommandMsgV2 responseMsg = new CommandMsgV2();

            try
            {
                if (message.Contains("ClientID"))
                {
                    if (message.Contains("用户名") && message.Contains("密码"))
                    {
                        string sUserName = message.GetValue("用户名").ToString().Trim();
                        string sPassword = message.GetValue("密码").ToString().Trim();

                        string  sQuery = "select manage,company from Operator where valid=1 and login_name = '" + sUserName + "' and password = '******'";
                        DataSet ds;
                        ds = SqlHelper.ExecuteDataset(m_ConnStr, CommandType.Text, sQuery);

                        if (ds.Tables[0].Rows.Count == 1)
                        {
                            //用户名、密码正确
                            object[] objs     = ds.Tables[0].Rows[0].ItemArray;
                            string   sRight   = objs[0].ToString();
                            string   sCompany = ds.Tables[0].Rows[0]["company"].ToString();

                            //查询用户可管理的业务类型
                            sQuery = "select businesstype from Operator_BusinessType where login_name = '" + sUserName + "'";
                            ds.Tables.Clear();

                            ds = SqlHelper.ExecuteDataset(m_ConnStr, CommandType.Text, sQuery);

                            string sFilter = "";
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                object[] temps = dr.ItemArray;
                                sFilter += temps[0].ToString().Trim() + ",";
                            }

                            #region 先发命令给CM,通知客户端登陆成功
                            CommandMsgV2 MsgLogOK = new CommandMsgV2();
                            MsgLogOK.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                            MsgLogOK.SeqID          = CommandProcessor.AllocateID();
                            MsgLogOK.SetValue("ClientID", message.GetValue("ClientID"));
                            MsgLogOK.SetValue("RESPONSE_TO", message.SeqID);
                            MsgLogOK.SetValue("RESULT", "OK");
                            MsgLogOK.SetValue("BUSINESSTYPE", sFilter.Trim());
                            MsgLogOK.SetValue("RIGHT", sRight.Trim());
                            MsgLogOK.SetValue("COMPANY", sCompany.Trim());

                            CommandProcessor.instance().DispatchCommand(MsgLogOK);

                            #endregion


                            //发命令给AM,注册客户端
                            responseMsg.SeqID          = message.SeqID;
                            responseMsg.TK_CommandType = Constants.TK_CommandType.REGISTERCLIENT;
                            responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                            responseMsg.SetValue(Constants.MSG_PARANAME_AUTHORIZED, true);
                            responseMsg.SetValue("SERVERNAME", Constants.ALARM_SERVERNAME);
                            responseMsg.SetValue("Filter", sFilter.Trim());
                            responseMsg.SetValue("RIGHT", sRight.Trim());
                            responseMsg.SetValue("COMPANY", sCompany.Trim());

                            sQuery = "update Operator set lastlogintime = '" + DateTime.Now.ToString() + "' where login_name = '" + sUserName + "'";

                            SqlHelper.ExecuteNonQuery(m_ConnStr, CommandType.Text, sQuery);

                            Logger.Instance().SendLog("UM", "用户:" + sUserName + " 已登录到系统.");
                        }
                        else
                        {
                            //登录失败
                            responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                            responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                            responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                            responseMsg.SetValue("RESULT", "NOK");

                            Logger.Instance().SendLog("UM", "用户:" + sUserName + " 登录失败.");
                        }
                    }
                    else
                    {
                        //登录失败
                        responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                        responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                        responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                        responseMsg.SetValue("RESULT", "NOK");

                        Logger.Instance().SendLog("UM", "无效登录包");
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //登录失败
                    responseMsg.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                    responseMsg.SetValue("ClientID", message.GetValue("ClientID"));
                    responseMsg.SetValue("RESPONSE_TO", message.SeqID);
                    responseMsg.SetValue("RESULT", "NOK");

                    Logger.Instance().SendLog("UM", "登录时出现异常:" + ex.ToString());
                }
                catch { }
            }
            finally
            {
            }
            return(responseMsg);
        }
Exemplo n.º 20
0
        //private object m_LockCommunication = new int();
        private void _listener(object state)
        {
            int buflen = 0;

            byte[] buf = new byte[8192];
            //C5.LinkedList<byte> totalBuf = new C5.LinkedList<byte>();
            DefLib.Util.ArrayBuilder <byte> totalBuf = new DefLib.Util.ArrayBuilder <byte>();

            byte[] rest = null;

            try
            {
                //NetworkStream stream = m_Client.GetStream();

                m_ListenerClearEvent.Reset();

                while (Interlocked.Read(ref m_Run) == 1)
                {
                    if (Interlocked.Read(ref m_Run) == 0)
                    {
                        break;
                    }

                    try
                    {
                        totalBuf.Clear();

                        /// 读取Socket缓冲区
                        ///
                        while (true)
                        {
                            lock (m_Client)
                            {
                                if (!m_Client.Poll(100, SelectMode.SelectRead))
                                {
                                    break;
                                }
                            }

                            if (Interlocked.Read(ref m_Run) == 0)
                            {
                                totalBuf.Clear();
                                break;
                            }

                            buflen = 0;
                            lock (m_Client)
                            {
                                if (m_Client.Connected)
                                {
                                    buflen = m_Client.Receive(buf, buf.Length, SocketFlags.None);
                                }
                            }

                            if (buflen > 0)
                            {
                                totalBuf.Append(buf, buflen);
                                //for (int i = 0; i < buflen; ++i)
                                //    totalBuf.Add(buf[i]);
                            }
                            else
                            {
                                throw new CommException("读到零字节数据.");
                            }

                            if (totalBuf.Length > 102400)
                            {
                                break;
                            }
                        }

                        if (totalBuf.Length > 0)
                        {
                            if (rest != null)
                            {
                                totalBuf.Insert(0, rest, rest.Length);
                                //totalBuf.InsertAll(0, rest);
                                rest = null;
                            }

                            if (m_Extractor == null)
                            {
                                totalBuf.Clear();
                                continue;
                            }

                            //SendLog(totalBuf.Count + " Bytes recved: " + DumpByte2Str(totalBuf.ToArray()));

                            // 解析收到的数据
                            List <ICommunicationMessage> messages = m_Extractor.extractMessages(totalBuf.ToArray(), ref rest);

                            // 派发给侦听者
                            if (messages.Count > 0)
                            {
                                List <ICommunicationMessage> queue = new List <ICommunicationMessage>();
                                foreach (ICommunicationMessage command in messages)
                                {
                                    try
                                    {
                                        command.SetValue("ClientID", m_ClientID);

                                        if (command.TK_CommandType == Constants.TK_CommandType.KEEPALIVE)
                                        {
                                            command.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                                            command.SetValue("RESPONSE_TO", command.SeqID);
                                            command.SetValue("RESULT", "OK");
                                            command.SeqID = CommandProcessor.AllocateID();

                                            enqueueMessage(command);
                                            continue;
                                        }

                                        queue.Add(command);
                                    } // end try
                                    catch
                                    { }
                                } // end for

                                if (queue.Count > 0)
                                {
                                    m_ParentCommer.FilterResponse(queue);
                                }

                                if (queue.Count > 0)
                                {
                                    CommandProcessor.instance().DispatchCommands(queue);
                                }
                            } // end if messages.Count
                        }
                    }
                    catch (CommException commex)
                    {
                        throw new CommException(commex.ToString());
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("通讯异常:\n" + ex.ToString());
                    }

                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //SendLog(m_ClientInfo.ToString() + "侦听线程异常退出:\n" + ex.ToString());
                    m_ListenerClearEvent.Set();
                }
                catch { }

                try
                {
                    InvokeConnectionBroken(this, ex.Message);
                    return;
                }
                catch { }
            }
            finally
            {
                try
                {
                    m_ListenerClearEvent.Set();
                }
                catch { }
            }
        }
Exemplo n.º 21
0
        private void _accepter()
        {
            try
            {
                m_AccepterStopEvent.Reset();

                while (Interlocked.Read(ref m_Run) == 1)
                {
                    Socket newclient = m_Listener.Accept();//.AcceptTcpClient();

                    lock (m_ClientCommunicators)
                    {
                        if (m_ClientCommunicators.Count == m_MaxClients)
                        {
                            byte[] buf = System.Text.Encoding.Default.GetBytes("Client connection exceeds. New request is closing.");

                            try
                            {
                                newclient.Send(buf);
                                newclient.Shutdown(SocketShutdown.Both);
                                newclient.Close();
                            }
                            catch (Exception ex)
                            {
                                SendLog(ex.ToString());
                            }

                            continue;
                        }
                        else
                        {
                            try
                            {
                                //IPEndPoint ep = newclient.Client.RemoteEndPoint as IPEndPoint;
                                //byte[] addr = ep.Address.GetAddressBytes();
                                //long id = addr[3] * 0x10000000000L +
                                //    addr[2] * 0x100000000L +
                                //    addr[1] * 0x1000000L +
                                //    addr[0] * 0x10000L + ep.Port;
                                long          id   = CommManager.AllocateClientID();
                                ICommunicator comm = new AsyncCommunicator(this, id, newclient, new INTERPRETER(), new EXTRACTOR(), new ENCODER(), m_bCompress);

                                lock (m_ClientCommunicators)
                                    m_ClientCommunicators[id] = comm;

                                lock (m_ClientActiveCounter)
                                    m_ClientActiveCounter[id] = 0;

                                //newclient.NoDelay = true;
                                //newclient.LingerState = new LingerOption(false, 0);
                                //newclient.SendBufferSize = 2048;
                                //newclient.SendTimeout = 1000;

                                comm.onLog += new LogHandler(comm_onLog);
                                comm.onConnectionBroken += new ConnectionBrokenHandler(_HandleConnectionBroken);
                                comm.startWork();

                                // 发送报文注册客户端
                                MSGTYPE msg = new MSGTYPE();
                                msg.SeqID          = CommandProcessor.AllocateID();
                                msg.TK_CommandType = Constants.TK_CommandType.REGISTERCLIENT;
                                msg.SetValue("ClientID", id);
                                msg.SetValue("SERVERNAME", Name);
                                msg.SetValue(Constants.MSG_PARANAME_AUTHORIZED, false);
                                CommandProcessor.instance().DispatchCommand(msg);

                                SendLog("客户端 " + newclient.RemoteEndPoint.ToString() + " 连接到:" + Name);

                                SendLog(Name + "当前客户端的数量:" + m_ClientCommunicators.Count);

                                //int wt, iot;
                                //ThreadPool.GetAvailableThreads(out wt, out iot);
                                //SendLog("可用工作线程数: " + wt + " I/O线程数: " + iot);
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    //NetworkStream ns = newclient.GetStream();
                                    //if (ns != null)
                                    //    ns.Close();

                                    newclient.Close();
                                    SendLog(ex.ToString());
                                }
                                catch { }
                            }
                        }
                    } // endlock
                }
            }
            catch (Exception ex)
            {
                SendLog(ex.ToString());
            }
            finally
            {
                m_AccepterStopEvent.Set();
            }
        }
Exemplo n.º 22
0
        private void _accepterCallback(IAsyncResult ar)
        {
            Socket newclient = m_Listener.EndAccept(ar);

            lock (m_ClientCommunicators)
            {
                if (m_ClientCommunicators.Count == m_MaxClients)
                {
                    byte[] buf = System.Text.Encoding.Default.GetBytes("Client connection exceeds. New request is closing.");

                    try
                    {
                        newclient.Send(buf);
                        newclient.Shutdown(SocketShutdown.Both);
                        newclient.Close();
                    }
                    catch (Exception ex)
                    {
                        SendLog(ex.ToString());
                    }
                }
                else
                {
                    try
                    {
                        long          id   = CommManager.AllocateClientID();
                        ICommunicator comm = new AsyncCommunicator(this, id, newclient, new INTERPRETER(), new EXTRACTOR(), new ENCODER(), m_bCompress);

                        lock (m_ClientCommunicators)
                            m_ClientCommunicators[id] = comm;

                        lock (m_ClientActiveCounter)
                            m_ClientActiveCounter[id] = 0;

                        comm.onLog += new LogHandler(comm_onLog);
                        comm.onConnectionBroken += new ConnectionBrokenHandler(_HandleConnectionBroken);
                        comm.startWork();

                        // 发送报文注册客户端
                        MSGTYPE msg = new MSGTYPE();
                        msg.SeqID          = CommandProcessor.AllocateID();
                        msg.TK_CommandType = Constants.TK_CommandType.REGISTERCLIENT;
                        msg.SetValue("ClientID", id);
                        msg.SetValue("SERVERNAME", Name);
                        msg.SetValue(Constants.MSG_PARANAME_AUTHORIZED, false);
                        CommandProcessor.instance().DispatchCommand(msg);

                        SendLog("客户端 " + newclient.RemoteEndPoint.ToString() + " 连接到:" + Name);

                        SendLog(Name + "当前客户端的数量:" + m_ClientCommunicators.Count);

                        //int wt, iot;
                        //ThreadPool.GetAvailableThreads(out wt, out iot);
                        //SendLog("可用工作线程数: " + wt + " I/O线程数: " + iot);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            newclient.Close();
                            SendLog(ex.ToString());
                        }
                        catch { }
                    }
                }
            } // endlock

            if (Interlocked.Read(ref m_Run) == 1)
            {
                _asyncAccepter();
            }
        }
Exemplo n.º 23
0
        private void _recvCallback(IAsyncResult ar)
        {
            SocketError err_code;

            try
            {
                int buflen = m_Client.EndReceive(ar, out err_code);
                m_RecvDone.Set();

                if (err_code != SocketError.Success)
                {
                    InvokeConnectionBroken(this, new SocketException((int)err_code).Message);
                    return;
                }

                if (buflen == 0)
                {
                    InvokeConnectionBroken(this, "收到零字节数据.");
                    return;
                }

                totalBuf.Clear();
                totalBuf.Append(buf, buflen);
                if (rest != null)
                {
                    totalBuf.Insert(0, rest, rest.Length);
                    rest = null;
                }

                if (m_Extractor == null)
                {
                    totalBuf.Clear();
                    return;
                }

                //SendLog(totalBuf.Count + " Bytes recved: " + DumpByte2Str(totalBuf.ToArray()));

                // 解析收到的数据
                List <ICommunicationMessage> messages = m_Extractor.extractMessages(totalBuf.ToArray(), ref rest);

                // 派发给侦听者
                if (messages.Count > 0)
                {
                    ++m_RecvCount;
                    //DefLib.Util.Logger.Instance().SendLog("AsyncComm", "Received[" + ClientID + "]: " + m_RecvCount);

                    List <ICommunicationMessage> queue = new List <ICommunicationMessage>();
                    foreach (ICommunicationMessage command in messages)
                    {
                        try
                        {
                            command.SetValue("ClientID", m_ClientID);

                            if (command.TK_CommandType == Constants.TK_CommandType.KEEPALIVE)
                            {
                                command.TK_CommandType = Constants.TK_CommandType.RESPONSE;
                                command.SetValue("RESPONSE_TO", command.SeqID);
                                command.SetValue("RESULT", "OK");
                                command.SeqID = CommandProcessor.AllocateID();

                                enqueueMessage(command);
                                continue;
                            }

                            queue.Add(command);
                        } // end try
                        catch
                        { }
                    } // end for

                    if (queue.Count > 0)
                    {
                        m_ParentCommer.FilterResponse(queue);
                    }

                    if (queue.Count > 0)
                    {
                        CommandProcessor.instance().DispatchCommands(queue);
                    }
                } // end if messages.Count

                if (Interlocked.Read(ref m_Run) != 0)
                {
                    _recvAsync();
                }
            }
            catch (Exception ex)
            {
                m_RecvDone.Set();
                InvokeConnectionBroken(this, ex.ToString());
            }
            finally
            {
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// 命令处理程序
        /// </summary>
        /// <param name="message"></param>
        public void handleCommand(ICommunicationMessage message)
        {
            if (message.Contains(Constants.MSG_PARANAME_ADAPTER_NAME))
            {
                if (message.GetValue(Constants.MSG_PARANAME_ADAPTER_NAME).ToString().Trim() != Name)
                {
                    return;
                }
            }
            else
            {
                throw new Exception("Incoming package's name mismatched.");
            }

            CommandMsgV2 resp = new CommandMsgV2();

            resp.TK_CommandType = Constants.TK_CommandType.RESPONSE;
            resp.SeqID          = CommandProcessor.AllocateID();
            resp.SetValue(Constants.MSG_PARANAME_RESPONSE_TO, message.SeqID);
            try
            {
                if (message.Contains("ClientID"))
                {
                    resp.SetValue("ClientID", message.GetValue("ClientID"));
                }
                else
                {
                    throw new Exception("No ClientID in incoming package.");
                }
                //对应几个命令:启动、停止、退出、
                switch (message.TK_CommandType)
                {
                case Constants.TK_CommandType.ADAPTER_START:
                    if (Start())
                    {
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                    }
                    else
                    {
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK");
                    }

                    break;

                case Constants.TK_CommandType.ADAPTER_STOP:
                    if (Stop())
                    {
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                    }
                    else
                    {
                        resp.SetValue(Constants.MSG_PARANAME_RESULT, "NOK");
                    }

                    break;

                case Constants.TK_CommandType.ADAPTER_SHUTDOWN:
                    Shutdown();
                    break;

                case Constants.TK_CommandType.ADAPTER_GETRUNTIMEINFO:
                {
                    Process p = Process.GetCurrentProcess();
                    resp.SetValue("PROCESSID", p.Id.ToString());
                    resp.SetValue("THREADCOUNT", p.Threads.Count.ToString());
                    resp.SetValue("PHYMEMORY", p.WorkingSet64.ToString());
                    resp.SetValue("STATUS", GetStatus().ToString());
                    resp.SetValue("STARTTIME", p.StartTime.ToString());
                    resp.SetValue("CPUTIME", ((long)p.TotalProcessorTime.TotalMinutes).ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.ADAPTER_GETOMCLIST:    //重点
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in GetOMCList())
                    {
                        sb.Append(s);
                        sb.Append(",");
                    }

                    if (sb.Length > 0)
                    {
                        sb.Remove(sb.Length - 1, 1);
                    }

                    resp.SetValue("OMCLIST", sb.ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.ADAPTER_GETCURLOG:
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in GetCurrentLog())
                    {
                        sb.Append(s);
                        sb.Append(Environment.NewLine);
                    }

                    resp.SetValue("CURLOG", sb.ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.ADAPTER_GETLOGFILES:
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in GetLogFiles())
                    {
                        sb.Append(s);
                        sb.Append(",");
                    }

                    if (sb.Length > 0)
                    {
                        sb.Remove(sb.Length - 1, 1);
                    }

                    resp.SetValue("LOGFILES", sb.ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                default:
                    break;
                }

                CommandProcessor.instance().DispatchCommand(resp);
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog("AdapterController", ex.ToString());
            }
        }
Exemplo n.º 25
0
        protected void Init()
        {
            try
            {
                //获取应用程序运行路径
                string  path = AppDomain.CurrentDomain.BaseDirectory;
                DataSet DBds = new DataSet();

                //读入数据库连接参数
                DBds = MD5Encrypt.DES.instance().DecryptXML2DS(path + "conf.xml", 1);

                m_SysPara.Clear();
                foreach (DataRow r in DBds.Tables["Parameters"].Rows)
                {
                    m_SysPara.Add(r["name"].ToString(), r["value"].ToString());
                }

                m_CommClient = CommManager.instance().CreateCommClient <CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>(
                    m_SysPara["Adapter Name"].ToString(),
                    m_SysPara["Server IP"].ToString(),
                    Convert.ToInt32(m_SysPara["Server Port"]),
                    Convert.ToInt32(m_SysPara["Comm Timeout"]), true, false);

                m_CommClient.onLog += new TK_AlarmManagement.LogHandler(LogReceiver);

                #region Declear Adapter
                m_Adapter = new T();
                m_Adapter.ControllerPort = Convert.ToInt32(m_SysPara["Controller Port"]);
                m_Adapter.Name           = m_SysPara["Adapter Name"].ToString();
                m_Adapter.Interval       = Convert.ToInt32(m_SysPara["Retrieve Interval"]);
                m_Adapter.SvrID          = Convert.ToInt32(m_SysPara["SvrID"]);
                m_Adapter.EncodingStr    = m_SysPara["Encoding"];
                m_Adapter.Init(m_CommClient);
                #endregion

                DefLib.Util.Logger.Instance().SubscibeLog("", new DefLib.Util.Logger.LogFunction(LogReceiver));
                //m_Adapter.LogReceived += new TK_AlarmManagement.LogHandler(LogReceiver);
                m_Adapter.StateChanged += new StateChangeHandler(m_Adapter_StateChanged);

                m_Name = m_Adapter.Name;

                // 配置监控终端服务器
                List <Constants.TK_CommandType> acceptedCommands = new List <Constants.TK_CommandType>();
                acceptedCommands.Add(Constants.TK_CommandType.RESPONSE);

                List <Constants.TK_CommandType> superCommands = new List <Constants.TK_CommandType>();
                superCommands.Add(Constants.TK_CommandType.RESPONSE);

                m_ControllerServer = CommManager.instance().CreateCommServer <DefaultInterpreter, CommandMsgV2, TKMessageV2Extractor, TKMessageV2Encoder>("监控服务器",
                                                                                                                                                          acceptedCommands, superCommands,
                                                                                                                                                          Convert.ToInt32(m_SysPara["Controller Port"]),
                                                                                                                                                          Convert.ToInt32(m_SysPara["MaxController"]), 30, true, false);

                m_ControllerServer.onLog += new LogHandler(LogReceiver);

                acceptedCommands.Clear();
                superCommands.Clear();
                Dictionary <Constants.TK_CommandType, byte> empty = new Dictionary <Constants.TK_CommandType, byte>();
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_START, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_STOP, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETRUNTIMEINFO, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETOMCLIST, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETCURLOG, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_GETLOGFILES, this, empty);
                CommandProcessor.instance().registerReportHandler(Constants.TK_CommandType.ADAPTER_SHUTDOWN, this, empty);
            }
            catch (Exception ex)
            {
                Logger.Instance().SendLog("AdapterController", ex.ToString());
                throw ex;
            }
        }
Exemplo n.º 26
0
        public void handleCommand(ICommunicationMessage message)
        {
            CommandMsgV2 resp = new CommandMsgV2();

            resp.TK_CommandType = Constants.TK_CommandType.RESPONSE;
            resp.SeqID          = CommandProcessor.AllocateID();
            resp.SetValue(Constants.MSG_PARANAME_RESPONSE_TO, message.SeqID);
            try
            {
                if (message.Contains("ClientID"))
                {
                    resp.SetValue("ClientID", message.GetValue("ClientID"));
                }
                else
                {
                    throw new Exception("No ClientID in incoming package.");
                }

                switch (message.TK_CommandType)
                {
                case Constants.TK_CommandType.SERVER_GETRUNTIMEINFO:
                {
                    Process p = Process.GetCurrentProcess();
                    resp.SetValue("PROCESSID", p.Id.ToString());
                    resp.SetValue("THREADCOUNT", p.Threads.Count.ToString());
                    resp.SetValue("MAX_THREADCOUNT", 30 + (AlarmManager.instance().MaxAdapters + AlarmManager.instance().MaxClients + AlarmManager.instance().MaxControllers) * 2);
                    resp.SetValue("PHYMEMORY", p.WorkingSet64.ToString());

                    /// SystemInfo使用了性能计数器,有可能构造不出来
                    ///
                    resp.SetValue("AVAIL_PHYMEMORY", 0);
                    resp.SetValue("MAX_PHYMEMORY", 0);
                    resp.SetValue("CPUUSAGE", 0);

                    try
                    {
                        resp.SetValue("AVAIL_PHYMEMORY", SystemInfo.Instance.MemoryAvailable);
                        resp.SetValue("MAX_PHYMEMORY", SystemInfo.Instance.PhysicalMemory);
                        resp.SetValue("CPUUSAGE", (int)SystemInfo.Instance.CpuLoad);
                    }
                    catch { }

                    resp.SetValue("STATUS", AlarmManager.instance().GetStatus().ToString());
                    resp.SetValue("STARTTIME", p.StartTime.ToString());
                    resp.SetValue("CPUTIME", ((long)p.TotalProcessorTime.TotalMinutes).ToString());
                    resp.SetValue("ALARMCLIENTS", AlarmManager.instance().GetAlarmClientsNum().ToString());
                    resp.SetValue("MAX_ALARMCLIENTS", AlarmManager.instance().MaxClients);
                    resp.SetValue("ADAPTERCLIENTS", AlarmManager.instance().GetAdapterClientsNum().ToString());
                    resp.SetValue("MAX_ADAPTERCLIENTS", AlarmManager.instance().MaxAdapters);
                    resp.SetValue("ACTIVEALARMNUM", AlarmManager.instance().GetActiveAlarmsNum().ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.SERVER_GETCURLOG:
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in GetCurrentLog())
                    {
                        sb.Append(s);
                    }

                    resp.SetValue("CURLOG", sb.ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.SERVER_GETLOGFILES:
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in GetLogFiles())
                    {
                        sb.Append(s);
                        sb.Append(",");
                    }

                    if (sb.Length > 0)
                    {
                        sb.Remove(sb.Length - 1, 1);
                    }

                    resp.SetValue("LOGFILES", sb.ToString());
                    resp.SetValue(Constants.MSG_PARANAME_RESULT, "OK");
                }
                break;

                case Constants.TK_CommandType.MON_GETTERMINALSINFO:
                {
                    C5.HashDictionary <long, AdapterInfo> ads = new C5.HashDictionary <long, AdapterInfo>();
                    AlarmManager.instance().GetAdaptersInfo(ads);

                    resp.SetValue(Constants.MSG_PARANAME_TERMINALS_INFO, ads);
                }
                break;

                default:
                    break;
                }

                CommandProcessor.instance().DispatchCommand(resp);
            }
            catch (Exception ex)
            {
                Main_LogReceived("", ex.ToString());
            }
        }