public void ReceiveImage() { int GetImageLength; int GetImageArea; int RealImageLength; MemoryStream ms = new MemoryStream(); IPBindPoint_ForImage = new IPEndPoint(ServerIP, sPort + 1); IPBindPoint_ForImage = new IPEndPoint(((IPEndPoint)Client[0].RemoteEndPoint).Address, sPort + 1); senderp = (IPEndPoint)IPBindPoint_ForImage; Bitmap GetImageBit; //Thread.Sleep(10000); try { ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500); while (Client[0].Connected) { //Get Image Size //ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Receive(GetImageSize, 0, 4, SocketFlags.None); RealImageLength = BitConverter.ToInt32(GetImageSize, 0); Client[0].Receive(GetImageSize, 0, 4, SocketFlags.None); GetImageLength = BitConverter.ToInt32(GetImageSize, 0); if (GetImageLength == 0) { continue; } //Get Image Area /*ImageClient.Receive(GetImageAreaByte, 0, 4, SocketFlags.None); * GetImageArea = BitConverter.ToInt32(GetImageAreaByte, 0);*/ GetImageBytes = new byte[GetImageLength]; //ImageServer.Receive(GetImageBytes, 0, GetImageLength, SocketFlags.None); //ImageServer.ReceiveFrom(GetImageBytes, 0, GetImageLength, SocketFlags.None, ref senderp); int count = 0; int icount = 0; sw = false; do { try { GetByte = new byte[SizeForOne + 4]; for (int i = icount; i < GetImageLength / SizeForOne; i++) { //ChatBoxAdd(ImageServer.ReceiveFrom(GetByte, 0, SizeForOne + 4, SocketFlags.None, ref senderp).ToString()); ImageServer.BeginReceiveFrom(GetByte, 0, SizeForOne + 4, SocketFlags.None, ref senderp, new AsyncCallback(MessageCallBack), Tuple.Create(GetByte, 0, GetImageLength)); } Client[0].Send(new byte[4]); Client[0].Receive(new byte[4]); if (GetImageLength % SizeForOne != 0) { ImageServer.ReceiveFrom(GetImageBytes, GetImageLength - (GetImageLength % SizeForOne), GetImageLength % SizeForOne, SocketFlags.None, ref senderp); } sw = true; Client[0].Send(BitConverter.GetBytes(-1)); } catch (Exception Ex3) { ChatBoxAdd(Ex3.ToString()); ChatBoxAdd("UDP 데이터 소실 발생."); sw = false; icount = 0; Client[0].Send(BitConverter.GetBytes(-1)); break; Client[0].Send(BitConverter.GetBytes(icount)); } } while (!sw); try { if (sw == false) { throw new Exception(); } ms = new MemoryStream(); ms.Write(GetImageBytes, 0, (int)GetImageBytes.Length); ms.Position = 0; GetImageBytes = new byte[RealImageLength]; //var DecompressStream = new DeflateStream(ms, CompressionMode.Decompress,true); var DecompressStream = new GZipStream(ms, CompressionMode.Decompress, true); var DecompressedStream = new MemoryStream(); DecompressStream.CopyTo(DecompressedStream); DecompressStream.Close(); DecompressedStream.Position = 0; Bitmap Image = new Bitmap(DecompressedStream); //Bitmap Image = new Bitmap(ms); ChatBoxAdd("Success!"); MainPicture.MainPictureChange(Image); //pictureBox1Change(Image); Orginal_Image = Image; ms.Close(); DecompressedStream.Close(); ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Send(new byte[4]); sw = true; } catch (Exception ex) { ChatBoxAdd(ex.ToString()); ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Send(new byte[4]); sw = true; } GetImageBytes = null; //Thread.Sleep(100); GetImageBit = null; GC.Collect(0); GC.Collect(1); } } catch (Exception Ex2) { ChatBoxAdd(Ex2.ToString()); } }
static void Main( string[] args ) { // Read args ParseArgs(args); // Start up the GUI thread InitGUIThread(); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..." ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service" ); // Register the local agent singleton RemotingConfiguration.RegisterWellKnownServiceType( typeof( Agent ), "SwarmAgent", WellKnownObjectMode.Singleton ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels" ); // We're going to have two channels for the Agent: one for the actual Agent // application (IPC with infinite timeout) and one for all other remoting // traffic (TCP with infinite timeout that we monitor for drops) IpcChannel AgentIPCChannel = null; TcpChannel AgentTCPChannel = null; while( ( Ticking == true ) && ( ( AgentIPCChannel == null ) || ( AgentTCPChannel == null ) ) ) { try { if( AgentIPCChannel == null ) { // Register the IPC connection to the local agent string IPCChannelPortName = String.Format( "127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort ); AgentIPCChannel = new IpcChannel( IPCChannelPortName ); ChannelServices.RegisterChannel( AgentIPCChannel, false ); } if( AgentTCPChannel == null ) { // Register the TCP connection to the local agent AgentTCPChannel = new TcpChannel( Properties.Settings.Default.AgentRemotingPort ); ChannelServices.RegisterChannel( AgentTCPChannel, false ); } } catch (RemotingException Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of"); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again..."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace)); Thread.Sleep(3000); } catch (Exception Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace)); Thread.Sleep(3000); } } // if we're still ticking, we should have both of our channels initialized if( Ticking ) { Debug.Assert( AgentIPCChannel != null ); Debug.Assert( AgentTCPChannel != null ); } else { // Otherwise, we can simply return to exit return; } // Get the agent interface object using the IPC channel string LocalAgentURL = String.Format( "ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() ); LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent" ); // Init the local agent object (if this is the first call to it, it will be created now) bool AgentInitializedSuccessfully = false; try { AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id ); } catch( Exception Ex ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..." ); AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString() ); // Try again with the TCP channel, which is slower but should work LocalAgentURL = String.Format( "tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() ); LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL ); try { AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id ); if( AgentInitializedSuccessfully ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!" ); } } catch( Exception Ex2 ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error." ); AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString() ); ChannelServices.UnregisterChannel( AgentTCPChannel ); ChannelServices.UnregisterChannel( AgentIPCChannel ); return; } } // Only continue if we have a fully initialized agent if( ( LocalAgent != null ) && AgentInitializedSuccessfully ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running" ); // Loop until a quit/restart event has been requested while( !LocalAgent.ShuttingDown() ) { try { // If we've stopped ticking, notify the agent that we want to shutdown if( !Ticking ) { LocalAgent.RequestShutdown(); } // Maintain the agent itself LocalAgent.MaintainAgent(); // Maintain any running active connections LocalAgent.MaintainConnections(); // Maintain the Agent's cache if( CacheRelocationRequested ) { LocalAgent.RequestCacheRelocation(); CacheRelocationRequested = false; } if( CacheClearRequested ) { LocalAgent.RequestCacheClear(); CacheClearRequested = false; } if( CacheValidateRequested ) { LocalAgent.RequestCacheValidate(); CacheValidateRequested = false; } LocalAgent.MaintainCache(); // Maintain any running jobs LocalAgent.MaintainJobs(); // If this is a deployed application which is configured to auto-update, // we'll check for any updates and, if there are any, request a restart // which will install them prior to restarting #if !__MonoCS__ if( ( AgentApplication.DeveloperOptions.UpdateAutomatically ) && ( ApplicationDeployment.IsNetworkDeployed ) && (DateTime.UtcNow > NextUpdateCheckTime)) { if( CheckForUpdates() ) { LocalAgent.RequestRestart(); } NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1); } #endif } catch( Exception Ex ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message ); AgentApplication.Log( EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString() ); } // Sleep for a little bit Thread.Sleep( 500 ); } // Let the GUI destroy itself RequestQuit(); bool AgentIsRestarting = LocalAgent.Restarting(); // Do any required cleanup LocalAgent.Destroy(); ChannelServices.UnregisterChannel( AgentTCPChannel ); ChannelServices.UnregisterChannel( AgentIPCChannel ); // Now that everything is shut down, restart if requested if( AgentIsRestarting ) { ClearCache(); InstallAllUpdates(); Application.Restart(); } } }
private void toolStripButton1_Click(object sender, EventArgs e) { if (goodInput && !loading) { loading = true; toolStripButton1.Enabled = false; if (iterations >= 100000) { DialogResult option = MessageBox.Show("Running " + iterations + " simulations will " + "take approximately: " + getTime() + "\nDo you wish to continue?", "Alert", MessageBoxButtons.OKCancel); if (option == DialogResult.Cancel) { goto Done; } } try { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } } catch (Exception Ex0) { var nullErrorMessageBox = MessageBox.Show ("ERROR disposing old image file! \nOutput: " + Ex0.ToString(), "Alert", MessageBoxButtons.OK); } RscriptWriter(); userInputScript = rPathDest; Console.WriteLine("userInputScript: " + userInputScript); outputLocation = RpathFinder(); Console.WriteLine("outputLocation: " + outputLocation); try { RunFromCmd(userInputScript, userInputCSV, outputLocation, iterations.ToString(), distributionType); } catch (Exception Ex1) { var nullErrorMessageBox = MessageBox.Show ("ERROR on CMD process! \nOutput: " + Ex1.ToString(), "Alert", MessageBoxButtons.OK); } try { Cursor.Current = Cursors.WaitCursor; toolStripButton1.BackColor = Color.GreenYellow; if (iterations >= 10000000) { Thread.Sleep(Convert.ToInt32(iterations * 0.10)); } else if (iterations >= 100000 && iterations < 10000000) { Thread.Sleep(Convert.ToInt32(iterations * 0.30)); } else if (iterations >= 10000 && iterations < 100000) { Thread.Sleep(Convert.ToInt32(iterations * 0.50)); } else { Thread.Sleep(2500); } } catch (Exception Ex2) { var nullErrorMessageBox = MessageBox.Show ("ERROR waiting for process to complete! \nOuput: " + Ex2.ToString(), "Alert", MessageBoxButtons.OK); } try { pictureBox1.Image = Image.FromFile(RpathFinder() + @"\output.png"); } catch (Exception Ex3) { var nullErrorMessageBox = MessageBox.Show ("ERROR loading the image file! \nOuput: " + Ex3.ToString(), "Alert", MessageBoxButtons.OK); } Done: try { if (!string.IsNullOrWhiteSpace(userInputScript)) { DeleteTempFile(userInputScript); } //if (!string.IsNullOrWhiteSpace(userInputScript)) //DeleteTempFile(RpathFinder() + @"\output.png"); loading = false; maxWarning = false; minWarning = false; } catch (Exception Ex4) { var nullErrorMessageBox = MessageBox.Show ("ERROR on cleanup process! \nOutput: " + Ex4.ToString(), "Alert", MessageBoxButtons.OK); } } }