예제 #1
0
        protected virtual void Dispose(bool disposing)
        {
#if !MONO
            if (disposing)
            {
                if (m_PipeStream != null)
                {
                    if (m_AsyncResult != null)
                    {
                        /*
                         * try
                         * {
                         *  m_PipeStream.EndWaitForConnection(m_AsyncResult);
                         * }
                         * catch (Exception)
                         * {
                         * }
                         */
                        m_AsyncResult = null;
                    }
                    m_PipeStream.Dispose();
                    m_PipeStream = null;
                }
                if (m_Memory != null)
                {
                    m_Memory.Lock();
                    m_Memory.Unlock();
                    m_Memory.Dispose();
                    m_Memory = null;
                }
            }
#endif
            m_Disposed = true;
        }
예제 #2
0
 public static string NamedPipeServerClose(object pipeRaw)
 {
     object[] pipe = (object[])pipeRaw;
     System.IO.Pipes.NamedPipeServerStream namedPipe = (System.IO.Pipes.NamedPipeServerStream)pipe[0];
     namedPipe.Close();
     return(null);
 }
예제 #3
0
        static void Main(string[] args)
        {
            bool end=false;

            while (!end)
            {
                using (System.IO.Pipes.NamedPipeServerStream pipeServer =
                    new System.IO.Pipes.NamedPipeServerStream("testpipe", System.IO.Pipes.PipeDirection.In))
                {
                    Console.WriteLine("NamedPipeServerStream object created.");

                    // Wait for a client to connect
                    Console.Write("Waiting for client connection...");
                    pipeServer.WaitForConnection();

                    Console.WriteLine("Client connected.");
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(pipeServer))
                    {
                        // Display the read text to the console
                        string temp;
                        while ((temp = sr.ReadLine()) != null)
                        {
                            Console.WriteLine("Received from client: {0}", temp);
                        }
                    }
                }
            }
        }
예제 #4
0
        private async Task getInventory()
        {
            listBox_2_Inventory.Items.Add(String.Format("Getting inventory for product '{0}' ...", Properties.Settings.Default.pid));

            string url      = String.Format("http://www.{0}/on/demandware.store/Sites-adidas-{1}-Site/{2}/Product-GetVariants?pid={3}", Properties.Settings.Default.locale, Properties.Settings.Default.code, helpers.marketsList[Properties.Settings.Default.code], Properties.Settings.Default.pid);
            string pipename = System.Diagnostics.Process.GetCurrentProcess().Id.ToString() + "_sizechecking_1337";

            var pipe = new System.IO.Pipes.NamedPipeServerStream(pipename, System.IO.Pipes.PipeDirection.InOut, 1);

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo           = new System.Diagnostics.ProcessStartInfo();
            process.StartInfo.FileName  = "3s_atc - browser.exe";
            process.StartInfo.Arguments = url + " " + pipename;
            process.Start();

            Dictionary <string, Dictionary <string, string> > products = await Task.Run(() => helpers.getInventory(pipe));

            listBox_2_Inventory.Items.Clear();

            foreach (KeyValuePair <string, Dictionary <string, string> > entry in products)
            {
                listBox_2_Inventory.Items.Add(String.Format("{0} - Size: {1} - Quantity: {2}", entry.Key, products[entry.Key]["size"], products[entry.Key]["stockcount"]));
            }

            if (listBox_2_Inventory.Items.Count > 0 && listBox_2_Inventory.Items[1].ToString().Contains("Quantity"))
            {
                MessageBox.Show("Done!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                listBox_2_Inventory.Items.Add("Error!");
                MessageBox.Show("Error while getting inventory!", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Waiting for connection on named pipe mypipe");

            while (true)
            {
                System.IO.Pipes.NamedPipeServerStream namedPipeServerStream = new System.IO.Pipes.NamedPipeServerStream("mypipe");

                namedPipeServerStream.WaitForConnection();

                byte[] buffer = new byte[255];

                namedPipeServerStream.Read(buffer, 0, 255);

                string request = ASCIIEncoding.ASCII.GetString(buffer);

                Console.WriteLine(request);

                request = request.Trim('\0');

                if (request.ToLower() == "close")
                    break;

                namedPipeServerStream.Close();
            }
        }
예제 #6
0
        // ************************
        // メンバーメソッド
        //  --- 主となる処理(受付、受信、送信)
        // ************************



        //============
        // 受け付け処理用メソッド
        // クライアントからの接続の受け付けを、本メソッドを実行することで開始されます。
        public void Listen(string Send_Data)
        {
            // 送信データー
            SendData = Send_Data;
            // 受付開始時に起動させるメソッドを実行
            // (本クラスを利用する側のプログラムに、イベントを伝達
            //   するメソッドを実行)
            OnStartListen(DateTime.Now);


            try
            {
                // 名前付きパイプ操作用のオブジェクト(サーバー用)を生成
                pipeServer = new System.IO.Pipes.NamedPipeServerStream("acsl-pipe", System.IO.Pipes.PipeDirection.InOut, 1, System.IO.Pipes.PipeTransmissionMode.Byte, System.IO.Pipes.PipeOptions.Asynchronous);


                // 接続待機
                // クライアントが接続して来るのを待機する。
                // かつ、その後の処理を行なうメソッドを指定。
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception ex)
            {
                // エラー処理
                System.Windows.Forms.MessageBox.Show(ex.Message, "エラー通知");
            }
        }
예제 #7
0
파일: Program.cs 프로젝트: chanket/Worker
        protected static void StartScreenshot(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            string pipeName = args[0];

            using (System.IO.Pipes.NamedPipeServerStream pipeStream = new System.IO.Pipes.NamedPipeServerStream(pipeName))
            {
                try
                {
                    pipeStream.WaitForConnection();
                    if (pipeStream.IsConnected)
                    {
                        int    iWidth  = Screen.PrimaryScreen.Bounds.Width;
                        int    iHeight = Screen.PrimaryScreen.Bounds.Height;
                        Bitmap img     = new Bitmap(iWidth, iHeight);

                        Graphics gc = Graphics.FromImage(img);
                        gc.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(iWidth, iHeight));
                        img.Save(pipeStream, ImageFormat.Jpeg);

                        pipeStream.WaitForPipeDrain();
                    }
                }
                catch { }
            }
        }
 public ServerContext Shutdown()
 {
     if (this._serverPipe != null)
     {
         this._serverPipe.Close();
         this._serverPipe = null;
     }
     return(this);
 }
예제 #9
0
		static async Task StartServerActivatorAsync(string npname)
		{
			await Task.Delay(1);
			while (!ApplicationCTS.IsCancellationRequested)
			{
				bool everConnected = false;
				try
				{
					using (var nps = new System.IO.Pipes.NamedPipeServerStream(npname, System.IO.Pipes.PipeDirection.InOut
						, 1, System.IO.Pipes.PipeTransmissionMode.Byte
						, System.IO.Pipes.PipeOptions.Asynchronous | System.IO.Pipes.PipeOptions.WriteThrough, 65536, 65536))
					{
						await nps.WaitForConnectionAsync(ApplicationCTS.Token);
						everConnected = true;
						byte[] msg = System.Text.Encoding.ASCII.GetBytes(CurrentProcess.Id.ToString());
						await nps.WriteAsync(msg);
						await nps.FlushAsync();
						//nps.Disconnect(); //do not disconnect
						nps.Close();
					}
				}
				catch (Exception x)
				{
					if (ApplicationCTS.IsCancellationRequested)
						return;
					WriteDebugLine(x);
					if (!everConnected)
					{
						await Task.Delay(1000);
						continue;
					}
				}
				PostToAppThread(delegate
				{
					WriteDebugLine("ServerActivator");

					var mf = MainBrowser?.FindForm();
					if (mf?.Visible == true)
					{
						ActivateForm(mf);
						return;
					}
					var forms = WF.Application.OpenForms;
					for (var i = 0; i < forms.Count; i++)
					{
						var form = forms[i];
						if (!form.Visible)
							continue;

						//WindowsInterop.SetForegroundWindow(form.Handle);
						ActivateForm(form);
						break;
					}
				});
			}
		}
예제 #10
0
        public IPCBus(string path)
        {
            _downstream = new System.IO.Pipes.NamedPipeClientStream("com.h3m3.posix.sockets." + System.Diagnostics.Process.GetCurrentProcess().Id);
            _upstream   = new System.IO.Pipes.NamedPipeServerStream("com.h3m3.posix.sockets.SockServ");
            System.IO.Pipes.PipeSecurity downstreamACL = new System.IO.Pipes.PipeSecurity();

            downstreamACL.AddAccessRule(new System.IO.Pipes.PipeAccessRule(Environment.UserName, System.IO.Pipes.PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

            _downstream.SetAccessControl(downstreamACL);
        }
예제 #11
0
        //============
        // クライアント接続後処理メソッド
        // 本サーバーにクライアントが接続してきたら、本メソッドの処理を
        // 実行します。具体的には、まず、クライアントに要求電文(命令)
        // を提出するよう通知します(すなわち、これは、サーバーに接続さ
        // れたことをクライアントに通知することを意味しています)。次に、
        // クライアントから要求電文が送られてくるのを待機します。
        // 第1引数: 非同期操作のステータス
        private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // パイプの取得
                System.IO.Pipes.NamedPipeServerStream pipe_Server = (System.IO.Pipes.NamedPipeServerStream)iar.AsyncState;


                //------------
                // 非同期操作完了
                //------------


                // クライアントが接続するのを待機する非同期操作を終了します。
                pipe_Server.EndWaitForConnection(iar);


                // 以下の処理は、本サーバーにクライアントが接続された後に実行されます。
                // (それまで待機中となり、実行が開始されない)


                //------------
                // クライアントへ接続通知を送信
                //------------


                // ストリームに対して、文字データーを読み書きするオブジェクトを生成
                AccessStream ss = new AccessStream(pipe_Server);


                // 送信データーを書き込み
                //  --- クライアントに要求電文(命令)を提出するよう通知します。
                //      具体的には、
                //      「サーバーはクライアントに命令を提出するよう要求している」
                //      と言う意味の英文メッセージを名前付きパイプに書き込む。
                ss.WriteString(
                    "A connection succeeded.",
                    "shift_jis");


                //------------
                // クライアントから要求電文を受信
                //------------


                // 要求電文受信待機
                ReceiveOrder(this);
            }
            // 名前付きパイプが壊れているなどの異常が発生した場合
            catch (System.IO.IOException ex)
            {
                // エラー処理
                System.Windows.Forms.MessageBox.Show(ex.Message, "エラー通知");
            }
        }
예제 #12
0
        public static int GetClientProcessId(this System.IO.Pipes.NamedPipeServerStream pipeServer)
        {
            UInt32 nProcID;
            IntPtr hPipe = pipeServer.SafePipeHandle.DangerousGetHandle();

            if (Native.ProcessApi.GetNamedPipeClientProcessId(hPipe, out nProcID))
            {
                return((int)nProcID);
            }
            return(0);
        }
예제 #13
0
파일: Program.cs 프로젝트: chanket/Worker
        protected static void StartCamera(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            int    timeout  = 5000;
            string pipeName = args[0];

            if (args.Length >= 2)
            {
                int.TryParse(args[1], out timeout);
            }
            using (System.IO.Pipes.NamedPipeServerStream pipeStream = new System.IO.Pipes.NamedPipeServerStream(pipeName))
            {
                try
                {
                    pipeStream.WaitForConnection();
                    if (pipeStream.IsConnected)
                    {
                        Camera        camera = new Camera();
                        Task <Bitmap> task   = camera.CaptureImageAsync(timeout); //直接Wait这个task会产生死锁,因此异步开始、在后面循环判断执行结果。

                        while (task.Status != TaskStatus.RanToCompletion)
                        {
                            switch (task.Status)
                            {
                            case TaskStatus.Faulted: throw task.Exception;

                            case TaskStatus.Canceled: throw new TaskCanceledException();

                            default:
                            {
                                Thread.Sleep(1);
                                Application.DoEvents();
                            }
                            break;
                            }
                        }

                        Bitmap img = task.Result;
                        img.Save(pipeStream, ImageFormat.Jpeg);

                        pipeStream.WaitForPipeDrain();
                    }
                }
                catch { }
            }
        }
예제 #14
0
        public static ServerContext LaunchServer(string pipeName, string command, string[] args)
        {
            var serverPipe =
                new System.IO.Pipes.NamedPipeServerStream(
                    pipeName, System.IO.Pipes.PipeDirection.InOut);

            var startInfo = new System.Diagnostics.ProcessStartInfo(command);

            startInfo.Arguments = String.Join(" ", args);
            var childProc = System.Diagnostics.Process.Start(startInfo);

            serverPipe.WaitForConnection();

            return(new ServerContext(serverPipe, childProc));
        }
예제 #15
0
        public static void ipc()
        {
            // https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication
            System.IO.Pipes.NamedPipeServerStream pipeServer =
                new System.IO.Pipes.NamedPipeServerStream("testpipe"
                                                          , System.IO.Pipes.PipeDirection.InOut, 1);

            // Wait for a client to connect
            pipeServer.WaitForConnection();

            // pipeServer.Write(
            System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen("lul", 2);

            // System.IO.MemoryMappedFiles
        }
예제 #16
0
파일: Form1.cs 프로젝트: maziweis/studydemo
        private void StartPIPE()
        {
            while (true)
            {
                try
                {
                    //打开pipe管道,当易课程序启动时通过管道控制页面跳转
                    System.IO.Pipes.NamedPipeServerStream _pipeServer =
                        new System.IO.Pipes.NamedPipeServerStream("KSEXE", System.IO.Pipes.PipeDirection.InOut, 2);
                    _pipeServer.WaitForConnection();
                    StreamReader sr      = new StreamReader(_pipeServer);
                    string       recData = sr.ReadLine();
                    if (recData != string.Empty)
                    {
                        //MessageBox.Show("管道接收到的数据\n" + recData);
                        PIPEMod pm = new Helper().Deserialize <PIPEMod>(recData);
                        if (pm != null)
                        {
                            if (pm.FunName == "Load")
                            {
                                strArgs    = new string[1];
                                strArgs[0] = pm.FunData;//{"FunData":"{\"account\":\"mzw\",\"password\":\"CEDDDE06F9915A27\",\"webUrl\":\"http:\\/\\/192.168.3.187:6012\\/api\\/\",\"apiName\":\"Students\\/\",\"classID\":\"-1\",\"param\":\"AttLesson\\/Page\\/Teaching.aspx?BookID=707&UserID=49a92e48-1f39-4382-9273-0a0d521162c6&EditionID=18&SubjectID=3&GradeID=5&ClassID=-1&BookType=1&page=IndexPage&DXTP=true\",\"ClassName\":\"公共班级\",\"gradeName\":\"公共年级\",\"clsName\":\"公共班级\"}","FunName":"Load"}

                                wb.Load(ConfigurationManager.AppSettings["DefaultURL"] + "/DefaultW.aspx");
                            }
                            //从易课+客户端回调,返回学生ID,资源ID,题目下发编号,改变学生显示状态(点亮)
                            if (pm.FunName == "ResData")
                            {
                                wb.ExecuteScriptAsync("dianliangStu('" + pm.FunData + "');");
                            }
                        }
                    }
                    sr.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
예제 #17
0
        private static void StartIpcPipe()
        {
            //todo: impl a set of IPC APIs to perform some cmds. eg.Pause/Resume, Quit...
            //todo: Temporay IPC mechanism.
            var synCtx     = new WindowsFormsSynchronizationContext();//note: won't work with `SynchronizationContext.Current`
            var pipeThread = new Thread(() =>
            {
                while (true)
                {
                    using (var server = new System.IO.Pipes.NamedPipeServerStream("WGestures_IPC_API"))
                    {
                        server.WaitForConnection();

                        Debug.WriteLine("Clien Connected");
                        using (var reader = new StreamReader(server))
                        {
                            var cmd = reader.ReadLine();
                            Debug.WriteLine("Pipe CMD=" + cmd);

                            if (cmd == "ShowSettings")
                            {
                                synCtx.Post((s) =>
                                {
                                    Debug.WriteLine("Thread=" + Thread.CurrentThread.ManagedThreadId);
                                    ShowSettings();
                                    //ToggleTrayIconVisibility();
                                }, null);
                            }
                        }
                    }
                }
            })
            {
                IsBackground = true
            };

            pipeThread.Start();
        }
예제 #18
0
        public void StreamDataExchange_Pipes()
        {
            bool success   = false;
            bool completed = false;

            int    size    = 200000000;
            string message = GenerateMessage(size);

            var client = new System.IO.Pipes.NamedPipeClientStream("TESTPIPE");
            var server = new System.IO.Pipes.NamedPipeServerStream("TESTPIPE");

            var banchmarkTimer = new System.Diagnostics.Stopwatch();

            banchmarkTimer.Start();

            var reading = new Task(async delegate()
            {
                await client.ConnectAsync();

                try
                {
                    // Data to message format.
                    string receivedMessage = await StreamHandler.StreamReaderAsync <string>(client);

                    // Stoping banchmark.
                    banchmarkTimer.Stop();

                    // Validate data.
                    success   = receivedMessage.Equals(message);
                    completed = true;
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.Message);
                    return;
                }
            });

            var writing = new Task(async delegate()
            {
                // Wait client connection.
                await server.WaitForConnectionAsync();

                try
                {
                    // Sending message to stream.
                    await StreamHandler.StreamWriterAsync(server, message);
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.Message);
                    return;
                }
            });


            reading.Start();
            writing.Start();

            while (!completed)
            {
                Thread.Sleep(5);
            }

            float secondsFromStart = banchmarkTimer.ElapsedMilliseconds / (1000.0f);
            float sharedMBSize     = size / 1000000.0f;
            float speedMBpS        = sharedMBSize / secondsFromStart;

            Console.WriteLine("Transmission time: " + secondsFromStart + " seconds");
            Console.WriteLine("Transmisted: " + sharedMBSize + " MB");
            Console.WriteLine("Speed: " +
                              speedMBpS + " MB/s | " +
                              (speedMBpS * 8) + "Mb/s");


            client.Dispose();
            server.Dispose();

            Assert.IsTrue(success);
        }
예제 #19
0
        public void openConnection()
        {
            string  message = "";
            Boolean loop    = true;

            while (loop)
            {
                //set up the reciever pipe - this will listen for compute messages from the java plugin.
                using (System.IO.Pipes.NamedPipeServerStream _pipeServer = new System.IO.Pipes.NamedPipeServerStream(_recieverPipeName, System.IO.Pipes.PipeDirection.InOut, 5))
                {
                    Console.WriteLine("Named Pipe " + _recieverPipeName + " Started");
                    Console.WriteLine("Waiting for Client To Connect to " + _recieverPipeName);
                    //set up the broadcast pipe - this will send a message to the java plugin (preferably when the requested compute is complete)
                    using (System.IO.Pipes.NamedPipeServerStream _senderPipeServer = new System.IO.Pipes.NamedPipeServerStream(_senderPipeName, System.IO.Pipes.PipeDirection.InOut, 5))
                    {
                        //establish valid links for the recieving and sending pipes.
                        try
                        {
                            Console.WriteLine("Named Pipe " + _senderPipeName + " Started");
                            Console.WriteLine("Waiting for Client To Connect to " + _senderPipeName);
                            _pipeServer.WaitForConnection();
                            Console.WriteLine("Client Connected to " + _recieverPipeName);
                            _senderPipeServer.WaitForConnection();
                            Console.WriteLine("Client Connected to " + _senderPipeName);
                            //now that there are valid connections, establish stream readers and writers accordingly
                            StreamReader sr = new StreamReader(_pipeServer);
                            StreamWriter sw = new StreamWriter(_senderPipeServer);
                            sw.AutoFlush = true;
                            //this sr.ReadLine() will wait until a message has been sent from the java plugin.
                            message = sr.ReadLine();
                            //process the message
                            if (!Implementations.ParserFactory.ParserFactory.Instance.parse(message))
                            {
                                if (Implementations.ParserFactory.ParserFactory.Instance.isValid)
                                {
                                    sw.WriteLine("Compute Successful!");
                                }
                                else
                                {
                                    sw.WriteLine("Compute Failed! " + Implementations.ParserFactory.ParserFactory.Instance.message);
                                }
                            }

                            //ensure that the response
                            sw.WriteLine("Message Recieved: " + message);
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                _senderPipeServer.Close();
                            }
                            catch (Exception e1)
                            {
                            }
                            try
                            {
                                _pipeServer.Close();
                            }
                            catch (Exception e2)
                            {
                            }
                            Console.WriteLine(ex.InnerException);
                        }
                    }
                }
                if (message == "Exit")
                {
                    loop = false;
                }
            }
        }
예제 #20
0
        public EditorWorkProgressShowerInConsole()
        {
#if UNITY_EDITOR_WIN
            var pipeName = System.DateTime.Now.ToString("yyMMddHHmmss");
            var pipeout  = new System.IO.Pipes.NamedPipeServerStream("ProgressShowerInConsole" + pipeName, System.IO.Pipes.PipeDirection.Out);
            var pipein   = new System.IO.Pipes.NamedPipeServerStream("ProgressShowerInConsoleControl" + pipeName, System.IO.Pipes.PipeDirection.In);
            var arout    = pipeout.BeginWaitForConnection(null, null);
            var arin     = pipein.BeginWaitForConnection(null, null);

            var dir     = Application.dataPath + "/../";
            var tooldir = CapsModEditor.GetPackageOrModRoot(CapsEditorUtils.__MOD__) + "/~Tools~/";
            System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(tooldir + "ProgressShowerInConsole.exe", pipeName);
            si.WorkingDirectory = tooldir;
            _ExProc             = System.Diagnostics.Process.Start(si);

            var thd_Write = new System.Threading.Thread(() =>
            {
                try
                {
                    pipeout.EndWaitForConnection(arout);
                    var sw = new System.IO.StreamWriter(pipeout);
                    while (_MessageReady.WaitOne())
                    {
                        _MessageReady.Reset();
                        lock (_MessageQueue)
                        {
                            foreach (var line in _MessageQueue)
                            {
                                sw.WriteLine(line);
                            }
                            sw.Flush();
                            _MessageQueue.Clear();
                        }
                    }
                }
                finally
                {
                    pipeout.Dispose();
                }
            });
            thd_Write.Start();

            var thd_Read = new System.Threading.Thread(() =>
            {
                try
                {
                    pipein.EndWaitForConnection(arin);
                    var sr = new System.IO.StreamReader(pipein);
                    while (!_ExProc.HasExited)
                    {
                        var line = sr.ReadLine();
                        if (line != null)
                        {
                            if (line == "\uEE05Quit")
                            {
                                break;
                            }
                        }
                    }
                }
                finally
                {
                    _ShouldQuit = true;
                    thd_Write.Abort();
                    _MessageReady.Set();
                    pipein.Dispose();
                }
            });
            thd_Read.Start();
#endif
        }
예제 #21
0
 private void CreatePipe()
 {
     m_PipeStream = new System.IO.Pipes.NamedPipeServerStream(m_Appname + "_Pipe", System.IO.Pipes.PipeDirection.In,
                                                              1, System.IO.Pipes.PipeTransmissionMode.Byte, System.IO.Pipes.PipeOptions.Asynchronous);
     m_AsyncResult = m_PipeStream.BeginWaitForConnection(new AsyncCallback(result => HandleConnection(result)), null);
 }
예제 #22
0
 internal ServerContext(System.IO.Pipes.NamedPipeServerStream serverPipe, System.Diagnostics.Process childProc)
 {
     this._serverPipe = serverPipe;
     this._childProc  = childProc;
 }
예제 #23
0
        private static void StartIpcPipe()
        {
            //todo: impl a set of IPC APIs to perform some cmds. eg.Pause/Resume, Quit...
            //todo: Temporay IPC mechanism.
            var synCtx = new WindowsFormsSynchronizationContext();//note: won't work with `SynchronizationContext.Current`
            var pipeThread = new Thread(() =>
            {
                while (true)
                {
                    using (var server = new System.IO.Pipes.NamedPipeServerStream("WGestures_IPC_API"))
                    {
                        server.WaitForConnection();

                        Debug.WriteLine("Clien Connected");
                        using (var reader = new StreamReader(server))
                        {
                            var cmd = reader.ReadLine();
                            Debug.WriteLine("Pipe CMD=" + cmd);

                            if (cmd == "ShowSettings")
                            {
                                synCtx.Post((s) =>
                                {
                                    Debug.WriteLine("Thread=" + Thread.CurrentThread.ManagedThreadId);
                                    ShowSettings();
                                }, null);
                            }
                        }
                    }
                }
            }) { IsBackground = true };
            pipeThread.Start();
        }
예제 #24
0
파일: Editor.cs 프로젝트: scw000000/Engine
        public Editor()
        {
            InitializeComponent();
             this.WindowState = FormWindowState.Maximized;
             m_CurrentDirectory = Directory.GetCurrentDirectory();
             m_AssetsDirectory = m_CurrentDirectory + "\\Assets\\";

             m_SupportEditorPattern = new List<string>(){ "*.xml",
                                                "*.fragmentshader",
                                                "*.vertexshader",
                                                "*.lua"};
             for ( int i = 0; i < m_SupportEditorPattern.Count; i++)
            {
            m_SupportEditorPattern[i] = WildCardToRegular( m_SupportEditorPattern[i] );
            }

             // Setting all of splitter width in all comtainers
             int splitterWidth = 10;
             this.splitContainer1.SplitterWidth = splitterWidth;
             this.splitContainer2.SplitterWidth = splitterWidth;
             this.splitContainer_Left.SplitterWidth = splitterWidth;
             this.splitContainer_Mid.SplitterWidth = splitterWidth;
             this.splitContainer_Right.SplitterWidth = splitterWidth;

             int SDLWindowWidth = 1366;
             int SDLWindowHeight = 768;
             int lrPageWidth = ( this.splitContainer1.Width - SDLWindowWidth - 2 * splitterWidth - 8 ) / 2;
             this.splitContainer1.SplitterDistance = this.splitContainer1.Width - lrPageWidth - splitterWidth - 4;
             this.splitContainer2.SplitterDistance = this.splitContainer2.Width - SDLWindowWidth - splitterWidth;
             this.splitContainer_Mid.SplitterDistance = SDLWindowHeight;

             InitializeAssetTree();

             m_RedirectStringDelegate = new strDelegate( RedirectString );
             m_SetActorDataStringDelegate = new strDelegate( SetActorDataGrid );

             TextBoxWritter textBoxWritter = new TextBoxWritter( this.textBox_Console );
             Console.SetOut( textBoxWritter );

             Console.WriteLine( "Initializing output redirecting" );
             int id = System.Diagnostics.Process.GetCurrentProcess().Id; // make this instance unique
             m_ServerPipe = new System.IO.Pipes.NamedPipeServerStream( "consoleRedirect" + id, System.IO.Pipes.PipeDirection.In, 1 );
             m_ClientPipe = new System.IO.Pipes.NamedPipeClientStream( ".", "consoleRedirect" + id, System.IO.Pipes.PipeDirection.Out, System.IO.Pipes.PipeOptions.WriteThrough );
             m_ClientPipe.Connect();
             System.Runtime.InteropServices.HandleRef hr11 = new System.Runtime.InteropServices.HandleRef( m_ClientPipe, m_ClientPipe.SafePipeHandle.DangerousGetHandle() );
             SetStdHandle( -11, hr11.Handle ); // redirect stdout to my pipe
             SetStdHandle( -12, hr11.Handle ); // redirect error to my pipe
             Console.WriteLine( "Waiting for console connection" );
             m_ServerPipe.WaitForConnection(); //blocking
             Console.WriteLine( "Console connection complete." );

             m_DllRedirectThreadWorker = new DllRedirectThreadObject();
             m_DllRedirectThreadWorker.SetReader( m_ServerPipe );
             m_DllRedirectThread = new Thread( m_DllRedirectThreadWorker.Run );
             m_DllRedirectThread.Start();

             m_SDLThreadWorker = new SDLThreadObject( Handle, this.tabPageEX_World.Handle, this.splitContainer_Mid.Panel1.Width, this.splitContainer_Mid.Panel1.Height );
             m_SDLThread = new Thread( m_SDLThreadWorker.Run );
             m_SDLThread.Start();
        }
예제 #25
0
        public static object NamedPipeServerCreate(VmContext vm, string name, Value startFn, Value onDataFn, Value closeFn)
        {
            System.IO.Pipes.NamedPipeServerStream namedPipe = new System.IO.Pipes.NamedPipeServerStream(name, System.IO.Pipes.PipeDirection.In);
            System.IO.StreamReader reader = new System.IO.StreamReader(namedPipe);
            object[] output = new object[] { namedPipe, reader, startFn, onDataFn, closeFn };

            System.ComponentModel.BackgroundWorker bgWorker = new System.ComponentModel.BackgroundWorker();
            bgWorker.DoWork += (sender, e) =>
            {
                try
                {
                    namedPipe.WaitForConnection();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    return;
                }

                // TODO: this is based on the MessageHub format and needs to be rewritten in a more generic way.
                // Sending individual characters is probably a bad idea performance-wise, and so some sort of
                // batching heuristic needs to be made. This "length@payload" format needs to go into the actual
                // MessageHub code directly.
                int stringLength = 0;
                System.Text.StringBuilder buffer = new System.Text.StringBuilder();
                bool isLengthParsing             = true;
                while (true)
                {
                    int b = namedPipe.ReadByte();
                    if (isLengthParsing)
                    {
                        if (b == '@')
                        {
                            stringLength = int.Parse(buffer.ToString());
                            buffer.Clear();
                            if (stringLength == 0)
                            {
                                TranslationHelper.GetEventLoop(vm).ExecuteFunctionPointerNativeArgs(onDataFn, new object[] { "" });
                            }
                            else
                            {
                                isLengthParsing = false;
                            }
                        }
                        else
                        {
                            buffer.Append((char)b);
                        }
                    }
                    else
                    {
                        buffer.Append((char)b);
                        stringLength--;
                        if (stringLength == 0)
                        {
                            TranslationHelper.GetEventLoop(vm).ExecuteFunctionPointerNativeArgs(onDataFn, new object[] { buffer.ToString() });
                            buffer.Clear();
                            isLengthParsing = true;
                        }
                    }
                }
            };
            bgWorker.RunWorkerAsync();

            return(output);
        }
예제 #26
0
 //============
 // コンストラクタ
 // 第1引数: 送信データー
 public PipeServer()
 {
     // 名前付きパイプ操作用のオブジェクトをnullで初期化
     pipeServer = null;
 }