Exemplo n.º 1
1
		private static IEnumerator<Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) {
			// Each server object performs asynchronous operation on this pipe
			using (var pipe = new NamedPipeServerStream(
				"Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message,
				PipeOptions.Asynchronous | PipeOptions.WriteThrough)) {
				// Asynchronously accept a client connection
				pipe.BeginWaitForConnection(ae.End(), null);
				yield return 1;

				// A client connected, let's accept another client
				var aeNewClient = new AsyncEnumerator();
				aeNewClient.BeginExecute(PipeServerAsyncEnumerator(aeNewClient),
					aeNewClient.EndExecute);

				// Accept the client connection
				pipe.EndWaitForConnection(ae.DequeueAsyncResult());

				// Asynchronously read a request from the client
				Byte[] data = new Byte[1000];
				pipe.BeginRead(data, 0, data.Length, ae.End(), null);
				yield return 1;

				// The client sent us a request, process it
				Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult());

				// Just change to upper case
				data = Encoding.UTF8.GetBytes(
					Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray());

				// Asynchronously send the response back to the client
				pipe.BeginWrite(data, 0, data.Length, ae.End(), null);
				yield return 1;

				// The response was sent to the client, close our side of the connection
				pipe.EndWrite(ae.DequeueAsyncResult());
			} // Close happens in a finally block now!
		}
Exemplo n.º 2
0
        private void BeginWaitForConnectionCallback(IAsyncResult iar)
        {
            pipeServer = (NamedPipeServerStream)iar.AsyncState;
            pipeServer.EndWaitForConnection(iar);

            if (pipeServer.IsConnected)
                pipeServer.BeginRead(receiveBuffer, 0, receiveBuffer.Length, BeginReadCallback, pipeServer);
        }
Exemplo n.º 3
0
        private void BeginReadCallback(IAsyncResult iar)
        {
            pipeServer = (NamedPipeServerStream)iar.AsyncState;
            int bytesRead = pipeServer.EndRead(iar);

            if (bytesRead > 0) {
                receiveMessage += System.Text.Encoding.UTF8.GetString(receiveBuffer, 0, receiveBuffer.Length);

                if (pipeServer.IsMessageComplete) {
                    OnReceiveMessageComplete(receiveMessage);
                    receiveMessage = "";
                }
            }

            pipeServer.BeginRead(receiveBuffer, 0, receiveBuffer.Length, BeginReadCallback, pipeServer);
        }
Exemplo n.º 4
0
        public void Initialize()
        {
            if (initialized)
                return;
            else
                initialized = true;

            // 初始化RenderControl
            KillExistingProcess();

            // 启动Pipe
            // NOTE 必须设置 Asynchronous
            pipeServer = new NamedPipeServerStream(
                "testpipe",
                PipeDirection.InOut,
                1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            inBuffer = new byte[1024];

            LogManager.Instance.Log("开始异步等待管道连接");
            pipeServer.BeginWaitForConnection(ar =>
            {
                pipeServer.EndWaitForConnection(ar);
                LogManager.Instance.Log("管道已连接");
                pipeServer.BeginRead(inBuffer, 0, pipeServer.InBufferSize, onClientDataReceived, pipeServer);
            }, pipeServer);

            // ProcessStartInfo info = new ProcessStartInfo(ConfigManager.Instance.Get("RenderAppPath"));
            ProcessStartInfo info = new ProcessStartInfo(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "./SpineRenderer/SpineRenderer.exe"));
            info.UseShellExecute = true;
            info.Arguments = " -popupwindow";
            
            // NOTE Hidden 会造成没有窗口句柄 unityProcess.MainWindowHandle == IntPtr.Zero
            // info.WindowStyle = ProcessWindowStyle.Minimized;
            // info.WindowStyle = ProcessWindowStyle.Normal;
            // info.WindowStyle = ProcessWindowStyle.Hidden;
            renderAppProcess = System.Diagnostics.Process.Start(info);

            // Wait for process to be created and enter idle condition
            LogManager.Instance.Log("开始等待渲染程序空闲");

            // NOTE thy 方法A在Win7上不管用,方法B在Win7/Win8上都OK
            // WaitForInputIdle 并不保证窗口句柄准备好

            // 方法-A
            // renderAppProcess.WaitForInputIdle(5000);

            // 方法-B
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            while (renderAppProcess.MainWindowHandle == IntPtr.Zero)
            {
                System.Threading.Thread.Sleep(100);
                // stopWatch.ElapsedMilliseconds > 
            }

            if (renderAppProcess.HasExited)
            {
                LogManager.Instance.Warn("内嵌程序已经退出");
            }
            else
            {
                LogManager.Instance.Log("内嵌程序初始化完成");
                LogManager.Instance.Log("检查内嵌程序句柄是否存在: " + renderAppProcess.MainWindowHandle.ToString());
            }
        }
Exemplo n.º 5
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int count = 0;
            BackgroundWorker worker = sender as BackgroundWorker;
            const int BufferSize = 256;
            System.Diagnostics.Debug.WriteLine("Start Background Worker");

            if (dataSource == SourceFrom.UART)
            {
                SkytraqGps gps = e.Argument as SkytraqGps;
                byte[] buff = new byte[BufferSize];
                try
                {
                    while (!worker.CancellationPending)
                    {
                        int l = gps.ReadLineNoWait(buff, 256, 1000);
                        if (buff[0] != 0xa0 || buff[1] != 0xa1 || buff[4] != 0x64 || buff[5] != 0xfd)
                        {
                            continue;
                        }
                        ++count;

                        worker.ReportProgress(count, new IQInfo(
                            buff[6],
                            (UInt32)buff[7] << 8 | (UInt32)buff[8],
                            buff[9],
                            buff[10],
                            buff[11],
                            buff[12],
                            buff[13],
                            (Int32)((UInt32)buff[14] << 24 | (UInt32)buff[15] << 16 | (UInt32)buff[16] << 8 | (UInt32)buff[17]),
                            (Int16)((UInt32)buff[18] << 8 | (UInt32)buff[19]),
                            (Int16)((UInt32)buff[20] << 8 | (UInt32)buff[21])));

                        //Console.WriteLine("{0},{1},{2},{3},{4},{5}",
                        //    gpsType, nmeaSvid, integrateionTime, doppler, iValue, qValue);
                    }
                }
                catch (Exception ep)
                {
                    Console.WriteLine(ep.ToString());
                }
            }
            else
            {
                //Initial Namedpipe ===========================================
                while (!worker.CancellationPending)
                {
                    System.Diagnostics.Debug.WriteLine("Pipe name :" + Program.pipeName);
                    using (NamedPipeServerStream pipeStream = new NamedPipeServerStream(Program.pipeName,
                        PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                    {
                        ReceiveStatus rs = ReceiveStatus.None;
                        int packageSize = 0;
                        int ptr = 0;
                        int sharpLen = 0;
                        byte[] buff = new byte[BufferSize];
                        System.Diagnostics.Debug.WriteLine("Create Named Pipe :" + Program.pipeName);
                        //Wait for connection
                        while (!worker.CancellationPending)
                        {
                            try
                            {
                                if (!pipeStream.IsConnected)
                                {
                                    //pipeStream.WaitForConnection();
                                    var asyncResult = pipeStream.BeginWaitForConnection(null, null);
                                    while (!worker.CancellationPending)
                                    {
                                        if (asyncResult.AsyncWaitHandle.WaitOne(5))
                                        {
                                            pipeStream.EndWaitForConnection(asyncResult);
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception ep)
                            {
                                Console.WriteLine(ep.ToString());
                                Thread.Sleep(10);
                                break;
                            }

                            if (worker.CancellationPending)
                            {
                                return;
                            }

                            var asyncResult2 = pipeStream.BeginRead(buff, ptr, 1, null, null);
                            //Wait for data in
                            while (!worker.CancellationPending)
                            {
                                if (asyncResult2.AsyncWaitHandle.WaitOne(5))
                                {
                                    pipeStream.EndRead(asyncResult2);
                                    ++ptr;
                                    break;
                                }
                            }

                            if (worker.CancellationPending)
                            {
                                return;
                            }
                            System.Diagnostics.Debug.Write(buff[ptr - 1]);

                            if (rs == ReceiveStatus.None && buff[ptr - 1] == '#')
                            {
                                rs = ReceiveStatus.GetSharpCommand;
                            }
                            else if (rs == ReceiveStatus.GetSharpCommand && buff[ptr - 1] == 0x0d)
                            {
                                rs = ReceiveStatus.GetSharpSlashR;
                                sharpLen = ptr - 1;
                            }
                            else if (rs == ReceiveStatus.GetSharpSlashR && buff[ptr - 1] == 0x0a)
                            {
                                rs = ReceiveStatus.FinishSharpCommand;
                            }
                            else if (rs == ReceiveStatus.GetSharpSlashR && buff[ptr - 1] != 0x0a)
                            {
                                rs = ReceiveStatus.GetSharpCommand;
                            }
                            else if (rs == ReceiveStatus.None && buff[ptr - 1] == 0xA0)
                            {
                                rs = ReceiveStatus.GetA0;
                            }
                            else if (rs == ReceiveStatus.GetA0 && buff[ptr - 1] == 0xA1)
                            {
                                rs = ReceiveStatus.GetA1;
                            }
                            else if (rs == ReceiveStatus.GetA1)
                            {
                                packageSize = buff[ptr - 1] << 8;
                                rs = ReceiveStatus.GetSize1;
                            }
                            else if (rs == ReceiveStatus.GetSize1)
                            {
                                packageSize |= buff[ptr - 1];
                                rs = ReceiveStatus.GetSize2;
                            }
                            else if (rs == ReceiveStatus.GetSize2)
                            {
                                if (ptr > (7 + packageSize) || ptr == BufferSize)
                                {
                                    ptr = 0;
                                    rs = ReceiveStatus.None;
                                }
                                if (ptr == (6 + packageSize) && buff[ptr - 1] == 0x0d)
                                {
                                    rs = ReceiveStatus.GetSlashR;
                                }
                            }
                            else if (rs == ReceiveStatus.GetSlashR && buff[ptr - 1] == 0x0a)
                            {
                                rs = ReceiveStatus.FinishBinCommand;
                            }
                            else if (buff[ptr - 1] == 0x0d)
                            {
                                rs = ReceiveStatus.ErrorSlashR;
                            }
                            else if (rs == ReceiveStatus.ErrorSlashR && buff[ptr - 1] == 0x0a)
                            {
                                rs = ReceiveStatus.None;
                                ptr = 0;
                            }

                            if (rs == ReceiveStatus.FinishBinCommand)
                            {
                                if (buff[0] != 0xa0 || buff[1] != 0xa1 || buff[4] != 0x64 || buff[5] != 0xfd)
                                {
                                    rs = ReceiveStatus.None;
                                    ptr = 0;
                                    continue;
                                }
                                ++count;

                                worker.ReportProgress(count, new IQInfo(
                                    buff[6],
                                    (UInt32)buff[7] << 8 | (UInt32)buff[8],
                                    buff[9],
                                    buff[10],
                                    buff[11],
                                    buff[12],
                                    buff[13],
                                    (Int32)((UInt32)buff[14] << 24 | (UInt32)buff[15] << 16 | (UInt32)buff[16] << 8 | (UInt32)buff[17]),
                                    (Int16)((UInt32)buff[18] << 8 | (UInt32)buff[19]),
                                    (Int16)((UInt32)buff[20] << 8 | (UInt32)buff[21])));
                                rs = ReceiveStatus.None;
                                ptr = 0;
                            }

                            if (rs == ReceiveStatus.FinishSharpCommand)
                            {
                                string s2 = Encoding.UTF8.GetString(buff).Substring(0, sharpLen);
                                if(s2 == "#QUIT")
                                {
                                    Close();
                                    return;
                                }
                            }

                            if (ptr == BufferSize)
                            {
                                rs = ReceiveStatus.None;
                                ptr = 0;
                            }
                        }   //while(worker.CancellationPending)

                    }   //using (NamedPipeServerStream pipeStrea...
                }
            }   //if (dataSource == SourceFrom.UART) else
        }
Exemplo n.º 6
0
        /// <summary>
        /// Called when the pipe received a connection
        /// </summary>
        /// <param name="result"></param>
        private void Pipe_OnConnection(IAsyncResult result)
        {
            // Accept connection
            try
            {
                pipeServer.EndWaitForConnection(result);
            }
            catch (ObjectDisposedException)
            {
                // Pipe closed
                pipeServer.Close();
                pipeServer = null;
                WriteLog(LogType.Info, "Pipe is closed.");
                return;
            }

            // Start reading data
            pipeBuffer = new byte[PIPE_BUFFER_SIZE];
            pipeServer.BeginRead(pipeBuffer, 0, PIPE_BUFFER_SIZE, Pipe_OnData, null);
        }
Exemplo n.º 7
0
        private void QvxDataServerWorker()
        {
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1))
            {
                pipeServer.WaitForConnection();

                var buf = new byte[65536*20];
                object state = new object();
                while (running && pipeServer.IsConnected)
                {
                    var iar = pipeServer.BeginRead(buf, 0, buf.Length, null, state);
                    while (!iar.IsCompleted) Thread.Sleep(1);   // TODO: add Timeout possibility
                    var count = pipeServer.EndRead(iar);
                    Console.WriteLine("Date Read: " + count.ToString());//+ ASCIIEncoding.ASCII.GetString(buf, 0, count));
                    if (count > 0)
                    {
                        var sendBuf = new byte[count];
                        Array.Copy(buf, sendBuf, count);
                        lock (locksendQueue)
                        {
                            sendQueue.Add(sendBuf);
                        }
                    }
                }
                if (pipeServer.IsConnected) pipeServer.Close();
            }

            Console.WriteLine("PIPE finished");

            lock (locksendQueue)
            {
                sendQueue.Add(new byte[0]);
            }
            running = false;
            Console.WriteLine("Close QvxDataServerWorker");
        }