Beispiel #1
0
        public void SendLaunchOK(LaunchAppRequest request_, LaunchRequestResponse.ENUM_LAUNCH_STATUS status_, string appName_ = "")
        {
            LaunchRequestResponse response = new LaunchRequestResponse(0, status_)
            {
                RequestID = request_.Head.ID,
                LaunchRequestID = request_.Head.ID,
                AppName = appName_,
            };

            var observer = new IPEndPoint(IPAddress.Parse(request_.ControllerIP), request_.ControllerPort);
            int n = response.Serialize(_outData);
            //Debug.Log(string.Format("SendLaunchOK: {0} to {1}", response, observer));
            LogUtil.WriteLog(string.Format("SendLaunchOK: {0} to {1}", response, observer));
            //UDPEndpoint.SendTo(_outSocket, _outData, n, SocketFlags.None, observer);
            SendTo(_outSocket, _outData, n, SocketFlags.None, observer);
        }
Beispiel #2
0
        public void Update()
        {
            int n = 0;
            //LogUtil.WriteLog("CmdReceiver Update Enter");
            while ((n = _inSocket.Available) > 0)
            {
                LogUtil.WriteLog("CmdReceiver Update GetData");
                MessageHead head = null;
                n = ReceiveFrom(_inSocket, _inData, ref _inRemoteEp);

                head = Message.ParseHead(_inData, _inData.Length);
                if (head == null)
                    break;

                var remoteIP = (_inRemoteEp as IPEndPoint).Address;
                LogUtil.WriteLog(string.Format("remoteIP:{0}",remoteIP.ToString()));
                if (FilterIP != "" && FilterIP != remoteIP.ToString())
                {
                    continue;
                }

                switch (head.Type)
                {
                    case MessageType.REQUEST_LaunchPlayerFromService:
                        {
                            MsgRequestLaunchPlayerFromService launch = new MsgRequestLaunchPlayerFromService(0, 0);
                            launch.Deserialize(_inData, n);
                            launch.ControllerIP = remoteIP.ToString();
                            LogUtil.WriteLog(string.Format("Receive msg {0}",launch));
                            //启动应用程序
                            string errorMsg = string.Empty;

                            _exePath = launch.EXEPath;
                            string appDir = new DirectoryInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase).FullName;
                            string exePath = appDir + "\\" + exePathConfigFile;
                            LogUtil.WriteLog(exePath);

                            if (File.Exists(exePath))
                            {
                                try
                                {
                                    XmlDocument xmlDoc = new XmlDocument();
                                    xmlDoc.Load(exePath);
                                    XmlNode root = xmlDoc.SelectSingleNode("ExeConfig");
                                    XmlNode exePathNode = root.SelectSingleNode("ExePath");
                                    _exePath = exePathNode.InnerText;
                                    LogUtil.WriteLog("_exePath:" + _exePath);
                                }
                                catch (Exception ex)
                                {
                                    LogUtil.WriteLog("exception:"+ex.Message);
                                }
                            }
                            else
                            {
                                LogUtil.WriteLog(exePathConfigFile+"not exist");
                            }

                            //_exePath = "D:\\VideoPlayer.exe";
                            if (ProcessUtil.StartProgram(_exePath, "", ref errorMsg))
                            {
                                LogUtil.WriteLog(string.Format("StartProgram:Success"));

                                //发送反馈
                                LogUtil.WriteLog(string.Format("Send OK Ack Ip:{0} , Port:{1}",remoteIP.ToString(),launch.ControllerPort));
                                SendLaunchOK(launch, LaunchRequestResponse.ENUM_LAUNCH_STATUS.OK);
                                
                            }
                            else
                            {
                                LogUtil.WriteLog(string.Format("StartProgram:{0} Error", errorMsg));
                                LogUtil.WriteLog(string.Format("Send NotFound Ack Ip:{0} , Port:{1}", remoteIP.ToString(), launch.ControllerPort));
                                SendLaunchOK(launch, LaunchRequestResponse.ENUM_LAUNCH_STATUS.NotFound);
                            }
                            break;
                        }
                    case MessageType.REQUEST_ShutdownPlayer:
                        {
                            MsgRequestShutdownPlayer shutdown = new MsgRequestShutdownPlayer(0, 0);
                            shutdown.Deserialize(_inData, n);
                            shutdown.ControllerIP = remoteIP.ToString();
                            ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Receive msg REQUEST_ShutdownPlayer"));
                            LogUtil.WriteLog(string.Format("Receive msg {0}",shutdown));

                            _handleRequest.HandleShutdown(shutdown);

                            //string fileName = Path.GetFileName(_exePath);
                            //string processName = fileName.Substring(0, fileName.LastIndexOf('.'));
                            //LogUtil.WriteLog(string.Format("FileName : {0}, ProcessName : {1}",fileName,processName));
                            ////关闭应用程序
                            //string errorMsg = string.Empty;
                            //if (ProcessUtil.CloseProgram(_exePath,ref errorMsg))
                            //{
                            //    LogUtil.WriteLog(string.Format("CloseProgram:Success"));

                            //    LogUtil.WriteLog(string.Format("Send Shutdown Ack to Ip:{0} , Port:{1}",remoteIP.ToString(),shutdown.ControllerPort));
                            //    SendShutdownOK(shutdown, ShutdownRequestResponse.ENUM_SHUTDOWN_STATUS.OK);

                            //}
                            //else
                            //{
                            //    LogUtil.WriteLog(string.Format("CloseProgram:{0} Error", errorMsg));
                            //}
                           

                            break;
                        }
                    case MessageType.REQUEST_PingService:
                        {
                            ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Receive msg REQUEST_PingService"));
                            LogUtil.WriteLog(string.Format("Receive msg REQUEST_PingService"));
                            MsgRequestPingService ping = new MsgRequestPingService(0,0);
                            ping.Deserialize(_inData, n);
                            //反馈
                            LogUtil.WriteLog(string.Format("Ping Ack Ip: {0}, Port:{1}",remoteIP.ToString(),ping.ControllerPort));
                            SendPingOK(ping,remoteIP);
                            break;
                        }
                    case MessageType.REQUEST_BY_NAME:
                        {
                            ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Receive msg REQUEST_BY_NAME"));
                            //按照名称启动应用
                            //启动成功后向控制端发送alive
                            var msg = new RequestByName();
                            msg.Deserialize(_inData, _inData.Length);
                            switch (msg.Name)
                            {
                                case "RunBatchRequest":
                                    {
                                        //var batch = new RunBatchRequest();
                                        //batch.Deserialize(_inData, _inData.Length);
                                        //batch.ControllerIP = remoteIP.ToString();
                                        //OnMessage(batch);
                                    }
                                    break;
                                case "LaunchAppRequest":
                                    {
                                        var launchApp = new LaunchAppRequest();
                                        launchApp.Deserialize(_inData, _inData.Length);
                                        launchApp.ControllerIP = remoteIP.ToString();
                                        //OnMessage(launchApp);
                                        _handleRequest.HandleLaunch(launchApp);
                                        
                                    }
                                    break;
                                default:
                                    //Debug.LogWarning("Failed to handle Request: " + msg);
                                    LogUtil.WriteLog("Failed to handle Request: " + msg);
                                    break;
                            }
                            //break;
                        }
                        break;
                    //case MessageType.CMD_Register:
                    //    {
                            
                    //        MsgCmdRegister register = new MsgCmdRegister(((IPEndPoint)_inRemoteEp).Address.ToString(), 0);
                    //        register.Deserialize(_inData, _inData.Length);
                    //        LogUtil.WriteLog(string.Format("Receive msg{0}", register));
                    //        _nodeID = register.PlayerID;

                    //        MsgAckRegisterOK registerOK = new MsgAckRegisterOK(0, _nodeID);

                    //        _outPort = register.CmdPort;
                    //        _observer = new IPEndPoint(IPAddress.Parse(register.IP), _outPort);
                    //        _isRegister = true;
                    //        SendRegisterOK(registerOK);
                    //        break;
                    //    }
                    default:
                        {
                            LogUtil.WriteLog(string.Format("Error: msg<head:<id:{0}, type:{1}>>",head.ID,head.Type));
                            break;
                        }
                }
            }
        }
        public void HandleLaunch(LaunchAppRequest launch_)
        {
            ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Launch App: " + launch_.EXEPath + "..."));
            var info = string.Format("LaunchRequestHandler_Handle: \n{0}\n", launch_);

            info += string.Format("_state: {0}\n", _state);
            //Debug.Log(info);
            LogUtil.WriteLog(info);
            if (_state != STATE.Idle)
            {
                CmdChannel.SendLaunchOK(
                    launch_, LaunchRequestResponse.ENUM_LAUNCH_STATUS.IsRunning,
                    _currentRequest.EXEPath + "(Not Idle)");
            }
            else
            {
                _currentRequest = launch_;
                var exePath = launch_.EXEPath;
                if (!File.Exists(exePath))
                {
                    CmdChannel.SendLaunchOK(launch_, LaunchRequestResponse.ENUM_LAUNCH_STATUS.NotFound, exePath);
                }
                else
                {
                    var     processName = Path.GetFileNameWithoutExtension(exePath);
                    Process prevProcess;
                    if (ValidateSingleInstance(processName, out prevProcess))
                    {
                        try
                        {
                            _lastProcess = new Process();
                            var startInfo = _lastProcess.StartInfo;
                            startInfo.FileName         = exePath;
                            startInfo.Arguments        = launch_.Arguments;
                            startInfo.WorkingDirectory = Path.GetDirectoryName(exePath);

                            info  = "Startup process\n";
                            info += string.Format("startInfo.FileName: {0}\n", startInfo.FileName);
                            info += string.Format("startInfo.Arguments: {0}\n", startInfo.Arguments);
                            info += string.Format("startInfo.WorkingDirectory: {0}\n", startInfo.WorkingDirectory);
                            //Debug.Log(info);
                            LogUtil.WriteLog(info);
                            //有bug,好像启动不起来
                            bool res = _lastProcess.Start();
                            LogUtil.WriteLog("Startup res:" + res);
                            //if (!AlertService.Interop.CreateProcess(exePath, Path.GetDirectoryName(exePath), launch_.Arguments))
                            //{
                            //    LogUtil.WriteLog(string.Format("Start Program Inner Error"));
                            //}

                            Process[] currentRunEditingProcess = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exePath));
                            int       turn = 0;
                            while (currentRunEditingProcess == null || currentRunEditingProcess.Length == 0)
                            {
                                Thread.Sleep(1000);
                                turn++;
                                // 5秒之后视为程序启动失败
                                if (turn > 5)
                                {
                                    ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Launch App Failed"));
                                    LogUtil.WriteLog(string.Format("Start Program Inner Error after 5 seconds"));
                                    return;
                                }
                                currentRunEditingProcess = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exePath));
                            }
                            _lastProcess = currentRunEditingProcess[0];

                            ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Launch App Success"));

                            CmdChannel.SendLaunchOK(launch_, LaunchRequestResponse.ENUM_LAUNCH_STATUS.OK, exePath);
                            //向控制端发送alive反馈 todo
                            //StartCoroutine(RunLoop());
                            //Thread t = new Thread(KeepAliveLoop);
                            //t.Start();
                            LogUtil.WriteLog("Start KeepAliveLoop success");
                        }
                        catch (Exception ex)
                        {
                            //Debug.LogWarning(ex);
                            LogUtil.WriteLog(ex.Message);
                            CmdChannel.SendLaunchOK(launch_, LaunchRequestResponse.ENUM_LAUNCH_STATUS.Error, exePath);
                        }
                    }
                    else
                    {
                        ThreadStarter._instance.OnMessageSend(this, new MessageEventArgs("Process is already running"));
                        //Debug.Log("Process is already running");
                        LogUtil.WriteLog("Process is already running");
                        CmdChannel.SendLaunchOK(
                            launch_, LaunchRequestResponse.ENUM_LAUNCH_STATUS.IsRunning,
                            _currentRequest.EXEPath + "(Launched elsewhere)");
                        if (_lastProcess == null)
                        {
                            //Debug.Log("Use prevProcess as _lastProcess!");
                            LogUtil.WriteLog("Use prevProcess as _lastProcess!");
                            _lastProcess = prevProcess;
                            var startInfo = _lastProcess.StartInfo;
                            startInfo.FileName         = exePath;
                            startInfo.Arguments        = launch_.Arguments;
                            startInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                            //向控制端发送alive反馈 todo
                            //StartCoroutine(RunLoop());
                            //Thread t = new Thread(KeepAliveLoop);
                            //t.Start();
                            LogUtil.WriteLog("Start KeepAliveLoop success");
                        }
                    }
                }
            }
        }