EndWaitForConnection() public méthode

public EndWaitForConnection ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
Résultat void
Exemple #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!
		}
        public async void SendMessageAsync()
        {
            try
            {
                using (var pipe = new NamedPipeServerStream(verb, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
                using (var stream = new StreamWriter(pipe))
                {
                    var connectionTask = Task.Factory.FromAsync(pipe.BeginWaitForConnection, pipe.EndWaitForConnection, null);
                    var timeoutTask = Task.Delay(2000);
                    var firstTask = await Task.WhenAny(connectionTask, timeoutTask);
                    if (firstTask == timeoutTask)
                    {
                        pipe.EndWaitForConnection(connectionTask);
                        return;
                    }

                    stream.AutoFlush = true;
                    await stream.WriteLineAsync(selectedFile);
                }
            }
            catch (Exception exception)
            {
                //OnSendMessageException(pipeName, new MessengerExceptionEventArgs(exception));
            }
        }
Exemple #3
0
 private void ServerLoop()
 {
     while (_stopRequired)
     {
         _allDone.Reset();
         var pipeStream = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);                
         pipeStream.BeginWaitForConnection(asyncResult =>
                                               {                                                          
                                                   pipeStream.EndWaitForConnection(asyncResult);
                                                   _allDone.Set();
                                                   var thread = new Thread(ProcessClientThread);
                                                   thread.Start(pipeStream);
                                               }, null);
         _allDone.WaitOne();
     }
 }
Exemple #4
0
		static void SetupPipeWait(App app)
		{
			var pipe = new NamedPipeServerStream(IPCName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
			pipe.BeginWaitForConnection(result =>
			{
				pipe.EndWaitForConnection(result);

				var buf = new byte[sizeof(int)];
				pipe.Read(buf, 0, buf.Length);
				var len = BitConverter.ToInt32(buf, 0);
				buf = new byte[len];
				pipe.Read(buf, 0, buf.Length);
				var commandLine = Coder.BytesToString(buf, Coder.CodePage.UTF8);

				app.Dispatcher.Invoke(() => app.CreateWindowsFromArgs(commandLine));

				SetupPipeWait(app);
			}, null);
		}
Exemple #5
0
        void pipeServerThread(object o)
        {
            NamedPipeServerStream pipeServer = null;
            try
            {
                while (true)
                {
                    pipeServer = new NamedPipeServerStream(
                        this.ServerName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                    IAsyncResult async = pipeServer.BeginWaitForConnection(null, null);
                    int index = WaitHandle.WaitAny(new WaitHandle[] { async.AsyncWaitHandle, closeApplicationEvent });
                    switch (index)
                    {
                        case 0:
                            pipeServer.EndWaitForConnection(async);
                            using (StreamReader sr = new StreamReader(pipeServer))
                            using (StreamWriter sw = new StreamWriter(pipeServer))
                            {
                                this.Recived(this, new ServerReciveEventArgs(sr, sw));
                            }
                            if (pipeServer.IsConnected)
                            {
                                pipeServer.Disconnect();
                            }
                            break;
                        case 1:
                            return;
                    }
                }
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Launches the specifies process and sends the dto object to it using a named pipe
        /// </summary>
        /// <param name="dto">Dto object to send</param>
        /// <param name="processStartInfo">Process info for the process to start</param>
        /// <param name="syncProcessName">Name of the pipe to write to</param>
        /// <returns>The started process</returns>
        public static Process LaunchProcessAndSendDto(NauDto dto, ProcessStartInfo processStartInfo, string syncProcessName)
        {
            Process p;

            using (NamedPipeServerStream pipe = new NamedPipeServerStream(syncProcessName, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
            {
                p = Process.Start(processStartInfo);

                if (p == null)
                {
                    throw new ProcessStartFailedException("The process failed to start");
                }

                var asyncResult = pipe.BeginWaitForConnection(null, null);

                if (asyncResult.AsyncWaitHandle.WaitOne(PIPE_TIMEOUT))
                {
                    pipe.EndWaitForConnection(asyncResult);

                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(pipe, dto);
                }
                else if (p.HasExited)
                {
                    Type exceptionType = Marshal.GetExceptionForHR(p.ExitCode).GetType();

                    throw new TimeoutException(string.Format("The NamedPipeServerStream timed out waiting for a named pipe connection, " +
                        "but the process has exited with exit code: {0} ({1})", p.ExitCode, exceptionType.FullName));
                }
                else
                {
                    throw new TimeoutException("The NamedPipeServerStream timed out waiting for a named pipe connection.");
                }
            }

            return p;
        }
 public ShellCommandHandler(CommandHandler cmdHandler)
 {
     pipeServer = new NamedPipeServerStream("sciGitPipe", PipeDirection.In, 1, PipeTransmissionMode.Byte,
                                      PipeOptions.Asynchronous);
       pipeThread = new Thread(() => {
     while (true) {
       try {
     var ar = pipeServer.BeginWaitForConnection(null, null);
     pipeServer.EndWaitForConnection(ar);
     var ss = new StreamString(pipeServer);
     string verb = ss.ReadString();
     string filename = ss.ReadString();
     cmdHandler(verb, filename);
     pipeServer.Disconnect();
       } catch (ObjectDisposedException) {
     break;
       } catch (IOException) {
     break;
       } catch (Exception e) {
     Logger.LogException(e);
       }
     }
       });
 }
Exemple #8
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());
            }
        }
        public async Task<Stream> RunAsync(Stream output, string query, params string[] sqlArguments)
        {
            NamedPipeServerStream pipeServerStream = new NamedPipeServerStream("SqlBcpWrapper" + GetHashCode(), PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            pipeServerStream.BeginWaitForConnection(e =>
            {
                pipeServerStream.EndWaitForConnection(e);

                while (pipeServerStream.IsConnected && !pipeServerStream.IsMessageComplete)
                {
                }

                pipeServerStream.CopyTo(output);
                output.Seek(0, SeekOrigin.Begin);
                pipeServerStream.Disconnect();
                pipeServerStream.Close();
            }, this);
            
            RunInternal("\\\\.\\pipe\\SqlBcpWrapper" + GetHashCode(), query, sqlArguments, null, null);

            await Task.Run(() =>
            {
                while (pipeServerStream.IsConnected && !pipeServerStream.IsMessageComplete)
                {
                }
            });

            return output;
        }
Exemple #10
0
 /// <summary>
 /// Initialises the named pipe server and waits for a connection
 /// </summary>
 /// <param name="pipe">The name of the pipe to create</param>
 /// <returns>True if a connection is received. Otherwise false.</returns>
 public bool Init(string pipe)
 {
     bool OK = Disconnect();
     if (OK)
     {
         try
         {
             ThePipe = new NamedPipeServerStream(pipe, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
             ThePipe.ReadMode = PipeTransmissionMode.Byte;
             ThePipe.BeginWaitForConnection(new AsyncCallback(delegate(IAsyncResult result)
             {
                 try
                 {
                     ThePipe.EndWaitForConnection(result);
                     
                     if (OnConnected != null)
                     {
                         OnConnected();
                     }
                 }
                 catch
                 {
                     //Ignore as probably error while terminating
                 }
             }), null);
         }
         catch
         {
             OK = false;
             ThePipe = null;
         }
     }
     return OK;
 }
Exemple #11
0
        private async Task ReadNamedPipeAsync()
        {
            string pipeID = pID.ToString();

            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("luaPipeR" + pipeID, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
            {
                await Task.Factory.FromAsync((cb, state) => pipeServer.BeginWaitForConnection(cb, state), ar => pipeServer.EndWaitForConnection(ar), null);

                using (StreamReader pipeReader = new StreamReader(pipeServer))
                {
                    await TaskScheduler.Default;

                    while (this.keepReadPipeOpen)
                    {
                        string command = await pipeReader.ReadLineAsync();

                        switch (command)
                        {
                            case "BreakpointHit":
                            {
                                debugThread.SourceFile = await pipeReader.ReadLineAsync();
                                debugThread.Line = uint.Parse(await pipeReader.ReadLineAsync());
                                debugThread.FuncName = await pipeReader.ReadLineAsync();

                                // Receive Callstack
                                debugThread.FrameCount = int.Parse(await pipeReader.ReadLineAsync());

                                List<Frame> frames = new List<Frame>(debugThread.FrameCount);

                                for (int stackLineIndex = 0; stackLineIndex < debugThread.FrameCount; stackLineIndex++)
                                {
                                    string func = await pipeReader.ReadLineAsync();
                                    string source = await pipeReader.ReadLineAsync();
                                    string line = await pipeReader.ReadLineAsync();
                                    frames.Add(new Frame(func, source, line));
                                }

                                debugThread.StackFrames = frames;
                                    
                                int numberToRead = int.Parse(await pipeReader.ReadLineAsync());

                                List<Variable> variables = new List<Variable>(numberToRead);

                                for (int localIndex = 0; localIndex < numberToRead; localIndex++)
                                {
                                    variables.Add(new Variable(await pipeReader.ReadLineAsync(), await pipeReader.ReadLineAsync(), await pipeReader.ReadLineAsync()));
                                }

                                debugThread.NumberOfLocals = numberToRead;
                                debugThread.Locals = variables;
                                AD7BreakpointEvent.Send(this, breakpointManager.GetBoundBreakpoint(debugThread.SourceFile + debugThread.Line));
                                break;
                            }
                            case "BreakpointBound":
                                string fileandline = await pipeReader.ReadLineAsync();
                                AD7BoundBreakpoint boundbp = breakpointManager.GetBoundBreakpoint(fileandline);

                                AD7BreakpointBoundEvent boundBreakpointEvent = new AD7BreakpointBoundEvent(boundbp);
                                Send(boundBreakpointEvent, AD7BreakpointBoundEvent.IID, this);
                                break;
                            case "StepComplete":
                            {
                                debugThread.FrameCount = 1;
                                debugThread.SourceFile = await pipeReader.ReadLineAsync();
                                debugThread.Line = uint.Parse(await pipeReader.ReadLineAsync());
                                debugThread.FuncName = await pipeReader.ReadLineAsync();

                                // Receive Callstack
                                debugThread.FrameCount = int.Parse(await pipeReader.ReadLineAsync());

                                List<Frame> frames = new List<Frame>(debugThread.FrameCount);

                                for (int stackLineIndex = 0; stackLineIndex < debugThread.FrameCount; stackLineIndex++)
                                {
                                    string func = await pipeReader.ReadLineAsync();
                                    string source = await pipeReader.ReadLineAsync();
                                    string line = await pipeReader.ReadLineAsync();
                                    frames.Add(new Frame(func, source, line));
                                }

                                debugThread.StackFrames = frames;
                                    
                                int numberToRead = int.Parse(await pipeReader.ReadLineAsync());

                                List<Variable> variables = new List<Variable>(numberToRead);

                                for (int localIndex = 0; localIndex < numberToRead; localIndex++)
                                {
                                    variables.Add(new Variable(await pipeReader.ReadLineAsync(), await pipeReader.ReadLineAsync(), await pipeReader.ReadLineAsync()));
                                }

                                debugThread.NumberOfLocals = numberToRead;
                                debugThread.Locals = variables;


                                Send(new AD7StepCompleteEvent(), AD7StepCompleteEvent.IID, this);
                                break;
                            }
                        }
                    }
                }

            }
        }
    private void waitForAdditionalInstances(string[] args)
    {
        var accumulatedArgs = new List<string>(args);

        while (true)
        {
            var signal = new ManualResetEvent(false);
            using (var pipeServer = new NamedPipeServerStream(ipcNamedPipeGuid, PipeDirection.In, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            {
                pipeServer.BeginWaitForConnection(x =>
                {
                    // if timed out, stop waiting for a connection
                    if (signal.WaitOne(0))
                    {
                        signal.Close();
                        return;
                    }

                    pipeServer.EndWaitForConnection(x);
                    signal.Set();
                }, null);

                // no client connected to the pipe within the Timeout period
                if (!signal.WaitOne(Timeout, true))
                {
                    signal.Set();
                    break;
                }

                using (var sr = new StreamReader(pipeServer))
                {
                    int length = Convert.ToInt32(sr.ReadLine());
                    for (int i = 0; i < length; ++i)
                        accumulatedArgs.Add(sr.ReadLine());
                }
            }

            // new args have been added to accumulatedArgs, continue loop to listen for another client
        }

        ipcMutex.Close();
        Launching(this, new SingleInstanceEventArgs(accumulatedArgs.ToArray()));
    }
Exemple #13
0
        private static BuildResult OutOfProcessBuild (Dictionary<string, object> arguments, int startupTimeoutMs = 5000) {
            var jss = new JavaScriptSerializer {
                MaxJsonLength = 1024 * 1024 * 64
            };

            var argsJson = jss.Serialize(arguments);
            var pipeId = String.Format("JSIL.Build{0:X4}", (new Random()).Next());

            Console.Error.WriteLine("// Starting out-of-process solution build with ID '{0}'...", pipeId);

            using (var pipe = new NamedPipeServerStream(
                pipeId, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous
            )) {
                var psi = new ProcessStartInfo {
                    FileName = Process.GetCurrentProcess().MainModule.FileName,
                    Arguments = String.Format("--buildSolution {0}", pipeId),
                    WorkingDirectory = Environment.CurrentDirectory,
                    CreateNoWindow = false,
                    UseShellExecute = false,
                    ErrorDialog = false                    
                };
                var childProcess = Process.Start(psi);
                if (childProcess == null)
                    throw new InvalidOperationException("Failed to start child process");

                var connectedEvent = new ManualResetEventSlim(false);
                var exitedEvent = new ManualResetEventSlim(false);

                try {
                    var connectAR = pipe.BeginWaitForConnection((_) => connectedEvent.Set(), null);

                    try {
                        childProcess.Exited += (s, e) => exitedEvent.Set();
                        if (childProcess.HasExited)
                            exitedEvent.Set();
                    } catch {
                    }

                    WaitHandle.WaitAny(
                        new[] { connectedEvent.WaitHandle, exitedEvent.WaitHandle }, startupTimeoutMs
                    );

                    if (connectedEvent.IsSet) {
                        pipe.EndWaitForConnection(connectAR);
                    } else if (exitedEvent.IsSet) {
                        Console.Error.WriteLine("// Out-of-process solution build terminated unexpectedly with code {0}!", childProcess.ExitCode);
                        Environment.Exit(1);
                    } else {
                        Console.Error.WriteLine("// Out-of-process solution build timed out!");
                        Environment.Exit(2);
                    }

                    using (var sr = new StreamReader(pipe))
                    using (var sw = new StreamWriter(pipe)) {
                        sw.WriteLine(argsJson);
                        sw.Flush();
                        pipe.Flush();
                        pipe.WaitForPipeDrain();

                        var resultJson = sr.ReadLine();
                        var buildResult = jss.Deserialize<BuildResult>(resultJson);

                        Console.Error.WriteLine("// Out-of-process solution build completed successfully.");

                        return buildResult;
                    }
                } finally {
                    try {
                        if (!childProcess.HasExited)
                            childProcess.Kill();
                    } catch {
                    }

                    childProcess.Dispose();
                }
            }
        }
Exemple #14
0
        public bool StartServer(string strEventName, string strPipeName, Action<CMD_STREAM, CMD_STREAM> pfnCmdProc)
        {
            if (pfnCmdProc == null || strEventName.Length == 0 || strPipeName.Length == 0)
            {
                return false;
            }
            if (m_ServerThread != null)
            {
                return false;
            }

            m_StopFlag = false;
            m_PulseEvent = new AutoResetEvent(false);
            m_ServerThread = new Thread(new ThreadStart(() =>
            {
                using (EventWaitHandle eventConnect = new EventWaitHandle(false, EventResetMode.AutoReset, strEventName))
                using (NamedPipeServerStream pipe = new NamedPipeServerStream(
                           strPipeName.Substring(strPipeName.StartsWith("\\\\.\\pipe\\", StringComparison.OrdinalIgnoreCase) ? 9 : 0),
                           PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    while (m_StopFlag == false)
                    {
                        pipe.BeginWaitForConnection(asyncResult =>
                        {
                            try
                            {
                                if (m_StopFlag == false)
                                {
                                    pipe.EndWaitForConnection(asyncResult);
                                    m_PulseEvent.Set();
                                }
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        }, null);
                        eventConnect.Set();
                        m_PulseEvent.WaitOne();
                        if (pipe.IsConnected)
                        {
                            try
                            {
                                byte[] bHead = new byte[8];
                                if (pipe.Read(bHead, 0, 8) == 8)
                                {
                                    CMD_STREAM stCmd = new CMD_STREAM();
                                    stCmd.uiParam = BitConverter.ToUInt32(bHead, 0);
                                    stCmd.uiSize = BitConverter.ToUInt32(bHead, 4);
                                    stCmd.bData = stCmd.uiSize == 0 ? null : new byte[stCmd.uiSize];
                                    if (stCmd.uiSize == 0 || pipe.Read(stCmd.bData, 0, stCmd.bData.Length) == stCmd.bData.Length)
                                    {
                                        CMD_STREAM stRes = new CMD_STREAM();
                                        pfnCmdProc.Invoke(stCmd, stRes);
                                        if (stRes.uiParam == (uint)ErrCode.CMD_NEXT)
                                        {
                                            // Emun用の繰り返しは対応しない
                                            throw new InvalidOperationException();
                                        }
                                        else if (stRes.uiParam != (uint)ErrCode.CMD_NO_RES)
                                        {
                                            BitConverter.GetBytes(stRes.uiParam).CopyTo(bHead, 0);
                                            BitConverter.GetBytes(stRes.uiSize).CopyTo(bHead, 4);
                                            pipe.Write(bHead, 0, 8);
                                            if (stRes.uiSize != 0 && stRes.bData != null && stRes.bData.Length >= stRes.uiSize)
                                            {
                                                pipe.Write(stRes.bData, 0, (int)stRes.uiSize);
                                            }
                                        }
                                    }
                                }
                                pipe.WaitForPipeDrain();
                                pipe.Disconnect();
                            }
                            catch
                            {
                                // Read & Write 中に切断されると例外が起きるはずなので一応 catch しておく
                            }
                        }
                    }
                }
            }));
            m_ServerThread.Start();

            return true;
        }
            public override async Task<IAsyncTransport> CreateAsync(Address address)
            {
                NamedPipeServerStream server = new NamedPipeServerStream(address.Path, PipeDirection.InOut, 4,
                    PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
#if DOTNET
                await server.WaitForConnectionAsync();
#else
                await Task.Factory.FromAsync(
                    (c, s) => server.BeginWaitForConnection(c, s),
                    (r) => server.EndWaitForConnection(r),
                    null);
#endif
                return new NamedPipeTransport(server);
            }
Exemple #16
0
        private void doServerWork()
        {
            IsRunning = true;

            Helper.Logging.OnLogMessage("Starting CWSRestartServer for process communication", ServerService.MessageType.Info);

            PipeSecurity ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, System.Security.AccessControl.AccessControlType.Allow));
            serverStream = new NamedPipeServerStream(CWSProtocol.Settings.SERVERNAME, PipeDirection.InOut, 254, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);

            while (!_shouldStop)
            {
                wait = new EventWaitHandle(false, EventResetMode.ManualReset);

                serverStream.BeginWaitForConnection(ar =>
                    {
                        try
                        {
                            serverStream.EndWaitForConnection(ar);
                            if (serverStream.IsConnected)
                            {
                                //Helper.Logging.OnLogMessage("Module connected", ServerService.MessageType.Info);

                                StreamReader sr = new StreamReader(serverStream, System.Text.Encoding.UTF8, true, 2048, true);
                                string message = sr.ReadLine();

                                if (message != null)
                                {
                                    string[] messages = message.Split(new string[] { " " }, 3, StringSplitOptions.None);

                                    if (messages.Count() == 3 || messages.Count() == 2)
                                    {
                                        if (messages.Count() == 2 || messages.Count() == 3)
                                        {
                                            CWSProtocol.Commands.Action a = (CWSProtocol.Commands.Action)Enum.Parse(typeof(CWSProtocol.Commands.Action), messages[0]);
                                            CWSProtocol.Commands.Command c = (CWSProtocol.Commands.Command)Enum.Parse(typeof(CWSProtocol.Commands.Command), messages[1]);

                                            message = (messages.Count() == 3) ? messages[2] : "";

                                            switch (a)
                                            {
                                                case CWSProtocol.Commands.Action.GET:

                                                    switch (c)
                                                    {
                                                        case CWSProtocol.Commands.Command.IDENTIFY:
                                                            Helper.Logging.OnLogMessage(String.Format("{0} said hello", message), ServerService.MessageType.Info);
                                                            sendReply(CWSProtocol.Commands.Command.ACK, "", serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.STATISTICS:
                                                            //Helper.Logging.OnLogMessage("Statistics were requested by an external module", ServerService.MessageType.Info);

                                                            sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("ALIVE {0}", ServerService.Validator.IsRunning()), serverStream);

                                                            if (Statistics != null && Statistics.Enabled)
                                                            {
                                                                sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("TOTAL {0}", Statistics.Players.Count), serverStream);
                                                                sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("CURRENT {0}", Statistics.ConnectedPlayers.Count), serverStream);
                                                                sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("RUNTIME {0:00}:{1:00}:{2:00}", Statistics.Runtime.TotalHours, Statistics.Runtime.Minutes, Statistics.Runtime.Seconds), serverStream);
                                                                sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("ENABLED {0}", Statistics.Enabled), serverStream);

                                                                if (Statistics.StatisticsDB != null)
                                                                    sendReply(CWSProtocol.Commands.Command.STATISTICS, String.Format("STATISTICSFILE {0}", Statistics.StatisticsDB.DatabaseFile), serverStream);
                                                            }

                                                            sendReply(CWSProtocol.Commands.Command.ENDSTATISTICS, "", serverStream);

                                                            break;

                                                        case CWSProtocol.Commands.Command.START:
                                                            ServerService.Helper.General.StartServer();
                                                            break;

                                                        case CWSProtocol.Commands.Command.STOP:
                                                            ServerService.Helper.General.SendQuit();
                                                            break;

                                                        case CWSProtocol.Commands.Command.RESTART:
                                                            ServerService.Helper.General.RestartServer();
                                                            break;

                                                        case CWSProtocol.Commands.Command.KILL:
                                                            ServerService.Helper.General.KillServer();
                                                            break;

                                                        case CWSProtocol.Commands.Command.WATCHER:
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("ENABLED {0}", Helper.Watcher.Instance.IsRunning), serverStream);
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("BLOCKED {0}", Helper.Watcher.Instance.IsBlocked), serverStream);
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("TIMEOUT {0}", Helper.Watcher.Instance.IntervallSeconds.ToString()), serverStream);
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("CHECKINTERNET {0}", ServerService.Helper.Settings.Instance.CheckInternet), serverStream);
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("CHECKLAN {0}", ServerService.Helper.Settings.Instance.CheckLAN), serverStream);
                                                            sendReply(CWSProtocol.Commands.Command.WATCHER, String.Format("CHECKLOOPBACK {0}", ServerService.Helper.Settings.Instance.CheckLoopback), serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.LOG:
                                                            if (GetLog != null)
                                                            {
                                                                List<Helper.LogMessage> logEntries = GetLog();

                                                                try
                                                                {
                                                                    StreamWriter writer = new StreamWriter(serverStream, System.Text.Encoding.UTF8, 2048, true);

                                                                    foreach (Helper.LogMessage m in logEntries)
                                                                    {
                                                                        if (m != null)
                                                                        {
                                                                            StringBuilder b = new StringBuilder();
                                                                            b.AppendFormat("{0:HH:mm:ss}", m.Timestamp);
                                                                            b.Append(" ");
                                                                            b.Append(m.MessageType.ToString());
                                                                            b.Append(": ");
                                                                            b.Append(m.Message);
                                                                            b.Append(Environment.NewLine);

                                                                            writer.WriteLine(b.ToString());
                                                                        }
                                                                    }

                                                                    writer.Close();
                                                                }
                                                                catch (IOException ex)
                                                                {
                                                                    if (Debugger.IsAttached)
                                                                    {
                                                                        Debugger.Break();
                                                                        Debugger.Log(1, "server", ex.Message);
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                sendReply(CWSProtocol.Commands.Command.LOG, "", serverStream);
                                                            }
                                                            break;

                                                        case CWSProtocol.Commands.Command.CONNECTED:

                                                            List<PlayerInfo> connected;

                                                            if (Statistics.Enabled && (connected = new List<PlayerInfo>(Statistics.ConnectedPlayers)).Count > 0)
                                                            {
                                                                StreamWriter writer = new StreamWriter(serverStream, System.Text.Encoding.UTF8, 2048, true);

                                                                foreach (PlayerInfo ip in connected)
                                                                    writer.WriteLine(ip.Address.ToString());

                                                                writer.Close();
                                                            }
                                                            else
                                                            {
                                                                StreamWriter writer = new StreamWriter(serverStream, System.Text.Encoding.UTF8, 2048, true);
                                                                writer.WriteLine("");
                                                                writer.Close();
                                                            }

                                                            break;

                                                        case CWSProtocol.Commands.Command.ACCESSLIST:

                                                            List<AccessListEntry> entries = new List<AccessListEntry>(AccessControl.Instance.AccessList);

                                                            if ((Statistics.Enabled || ServerService.Helper.Settings.Instance.ExternalAccessControl) && entries.Count > 0)
                                                            {
                                                                StreamWriter writer = new StreamWriter(serverStream, System.Text.Encoding.UTF8, 2048, true);

                                                                foreach (AccessListEntry e in entries)
                                                                    writer.WriteLine(e.ToString());

                                                                writer.Close();
                                                            }
                                                            else
                                                            {
                                                                StreamWriter writer = new StreamWriter(serverStream, System.Text.Encoding.UTF8, 2048, true);
                                                                writer.WriteLine("");
                                                                writer.Close();
                                                            }

                                                            break;

                                                        case CWSProtocol.Commands.Command.ACCESSMODE:
                                                            sendReply(CWSProtocol.Commands.Command.ACCESSMODE, AccessControl.Instance.Mode.ToString(), serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.PLAYERSDATABASE:
                                                            Helper.Settings.Instance.SetUpPlayersdatabase();
                                                            sendReply(CWSProtocol.Commands.Command.PLAYERSDATABASE, Helper.Settings.Instance.KnownPlayersLocation, serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.PLAYERIDENTIFICATION:
                                                            if (Helper.Settings.Instance.PlayeridentificationEnabled)
                                                                sendReply(CWSProtocol.Commands.Command.PLAYERIDENTIFICATION, "ENABLED", serverStream);
                                                            else
                                                                sendReply(CWSProtocol.Commands.Command.PLAYERIDENTIFICATION, "DISABLED", serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.PREMIUMSLOTS:
                                                            if (Helper.Settings.Instance.PremiumslotsEnabled)
                                                                sendReply(CWSProtocol.Commands.Command.PREMIUMSLOTS, "ENABLED", serverStream);
                                                            else
                                                                sendReply(CWSProtocol.Commands.Command.PREMIUMSLOTS, "DISABLED", serverStream);
                                                            break;

                                                        case CWSProtocol.Commands.Command.PREMIUMDATABASE:
                                                            Helper.Settings.Instance.SetUpPremiumdatabase();
                                                            sendReply(CWSProtocol.Commands.Command.PREMIUMDATABASE, Helper.Settings.Instance.PremiumLocation, serverStream);
                                                            break;
                                                    }

                                                    break;
                                                case CWSProtocol.Commands.Action.POST:
                                                    switch (c)
                                                    {
                                                        case CWSProtocol.Commands.Command.LOG:
                                                            if (String.Compare(message, "clear", true) == 0)
                                                            {
                                                                if (ClearLog != null)
                                                                    ClearLog();
                                                            }
                                                            break;

                                                        case CWSProtocol.Commands.Command.WATCHER:
                                                            {
                                                                if (String.Compare(message, "start", true) == 0 && !Helper.Watcher.Instance.IsRunning)
                                                                    Helper.Watcher.Instance.Start();
                                                                else if (String.Compare(message, "stop", true) == 0 && Helper.Watcher.Instance.IsRunning && !Helper.Watcher.Instance.IsBlocked)
                                                                    Helper.Watcher.Instance.Stop();
                                                                else
                                                                {
                                                                    string[] parts = message.Split(new string[] { " " }, 2, StringSplitOptions.None);

                                                                    if (parts.Length == 2)
                                                                    {
                                                                        switch (parts[0])
                                                                        {
                                                                            case "TIMEOUT":
                                                                                UInt32 seconds;
                                                                                if (UInt32.TryParse(parts[1], out seconds))
                                                                                    Helper.Watcher.Instance.IntervallSeconds = seconds;
                                                                                break;
                                                                            case "ACCESS":
                                                                                parts = parts[1].Split(' ');
                                                                                if (parts.Length == 6)
                                                                                {
                                                                                    for (int i = 0; i < parts.Length; i = i + 2)
                                                                                    {
                                                                                        bool check;
                                                                                        if (Boolean.TryParse(parts[i + 1], out check))
                                                                                        {
                                                                                            switch (parts[i])
                                                                                            {
                                                                                                case "CHECKINTERNET":
                                                                                                    ServerService.Helper.Settings.Instance.CheckInternet = check;
                                                                                                    break;

                                                                                                case "CHECKLAN":
                                                                                                    ServerService.Helper.Settings.Instance.CheckLAN = check;
                                                                                                    break;

                                                                                                case "CHECKLOOPBACK":
                                                                                                    ServerService.Helper.Settings.Instance.CheckLoopback = check;
                                                                                                    break;
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                                break;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            break;

                                                        case CWSProtocol.Commands.Command.KICK:
                                                            IPAddress ip;
                                                            if (IPAddress.TryParse(message, out ip))
                                                            {
                                                                ServerService.Helper.DisconnectWrapper.CloseRemoteIP(ip.ToString());
                                                            }
                                                            break;

                                                        case CWSProtocol.Commands.Command.ACCESSLIST:
                                                            string line;
                                                            List<AccessListEntry> entries = new List<AccessListEntry>();
                                                            AccessListEntry tmp;

                                                            if (AccessControl.GenerateEntryFromString(message, out tmp))
                                                                entries.Add(tmp);

                                                            while ((line = sr.ReadLine()) != null)
                                                            {
                                                                string[] parts = line.Split(new string[] { " " }, 3, StringSplitOptions.RemoveEmptyEntries);

                                                                if (parts.Length == 3 && parts[0] == CWSProtocol.Commands.Action.POST.ToString() && parts[1] == CWSProtocol.Commands.Command.ACCESSLIST.ToString() && !String.IsNullOrEmpty(parts[2]))
                                                                {
                                                                    if (AccessControl.GenerateEntryFromString(parts[2], out tmp))
                                                                        entries.Add(tmp);
                                                                }
                                                            }

                                                            AccessControl.Instance.SetAccessList(new System.Collections.ObjectModel.ObservableCollection<AccessListEntry>(entries));
                                                            break;

                                                        case CWSProtocol.Commands.Command.ACCESSMODE:
                                                            AccessMode mode;

                                                            if (System.Enum.TryParse<AccessMode>(message, out mode))
                                                                AccessControl.Instance.Mode = mode;

                                                            break;

                                                        case CWSProtocol.Commands.Command.PRESET:
                                                            string[] content = message.Split(new string[] { " " }, 2, StringSplitOptions.RemoveEmptyEntries);

                                                            if (content.Length == 2 && (content[0] == "DELETE" || content[0] == "PERSISTENT") && File.Exists(content[1]))
                                                            {
                                                                Helper.Settings.Instance.LoadPreset(content[1]);

                                                                if (content[0] == "DELETE")
                                                                    File.Delete(content[1]);
                                                            }

                                                            break;

                                                        case CWSProtocol.Commands.Command.PLAYERIDENTIFICATION:
                                                            if (message.ToLowerInvariant() == "enable")
                                                                Helper.Settings.Instance.PlayeridentificationEnabled = true;
                                                            else
                                                                Helper.Settings.Instance.PlayeridentificationEnabled = false;

                                                            Helper.Logging.OnLogMessage("Now ready to identify players...", ServerService.MessageType.Info);

                                                            break;

                                                        case CWSProtocol.Commands.Command.PREMIUMSLOTS:
                                                            if (message.ToLowerInvariant() == "enable")
                                                                Helper.Settings.Instance.PremiumslotsEnabled = true;
                                                            else
                                                                Helper.Settings.Instance.PremiumslotsEnabled = false;

                                                            Helper.Logging.OnLogMessage(Helper.Settings.Instance.PremiumslotsEnabled ? "Premium slots are enabled" : "Premium slots are disabled", ServerService.MessageType.Info);
                                                            break;

                                                        case CWSProtocol.Commands.Command.EXTERNALACCESSCONTROL:
                                                            if (message.ToLowerInvariant() == "enable")
                                                                ServerService.Helper.Settings.Instance.ExternalAccessControl = true;
                                                            else
                                                                ServerService.Helper.Settings.Instance.ExternalAccessControl = false;

                                                            Helper.Logging.OnLogMessage(ServerService.Helper.Settings.Instance.ExternalAccessControl ? "Access is controlled by an external program." : "Access to your server is controlled by CWSRestart.", ServerService.MessageType.Info);
                                                            break;

                                                    }
                                                    break;
                                            }
                                        }
                                    }
                                }

                                sr.Close();
                            }
                            serverStream.Disconnect();
                            wait.Set();
                        }
                        catch (ObjectDisposedException)
                        {
                            Helper.Logging.OnLogMessage("CWSRestartServer has been stopped", ServerService.MessageType.Info);
                            wait.Set();
                        }
                    }, null);

                wait.WaitOne();
            }

            serverStream.Close();
            IsRunning = false;
        }
Exemple #17
0
 private void clientConnected(IAsyncResult ar)
 {
     using (NamedPipeServerStream serverStream = new NamedPipeServerStream("CWSRestartServer", PipeDirection.In, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
     {
         serverStream.EndWaitForConnection(ar);
     }
 }
Exemple #18
0
            private void Worker(object state)
            {
                try {
                    var sourceUrl = (string)state;

                    lock (Mutex) {
                        Dispose();

                        string resolvedUrl = null;

                        ServerPipe = new NamedPipeServerStream("Stream Mosaic", PipeDirection.InOut, 64, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                        var connection = ServerPipe.BeginWaitForConnection(null, null);

                        var psi = new ProcessStartInfo(
                            Form.LivestreamerPath,
                            String.Format(
                                "--player-continuous-http --player StreamMosaic.exe \"{0}\" best",
                                sourceUrl
                            )
                        );
                        psi.UseShellExecute = false;
                        psi.CreateNoWindow = true;
                        psi.WindowStyle = ProcessWindowStyle.Hidden;
                        /*
                        psi.RedirectStandardError = true;
                        psi.RedirectStandardOutput = true;
                         */
                        LivestreamerProcess = Process.Start(psi);

                        connection.AsyncWaitHandle.WaitOne();
                        ServerPipe.EndWaitForConnection(connection);

                        var bytes = new byte[10240];
                        var numBytes = ServerPipe.Read(bytes, 0, bytes.Length);
                        resolvedUrl = Encoding.UTF8.GetString(bytes, 0, numBytes);

                        // We keep the pipe open so the child process survives, which keeps livestreamer's proxy alive.

                        var ar = Form.BeginInvoke(
                            (Action<int>)((index) => {
                                Form.Sources.Rows[index].Cells[1].Value = resolvedUrl;
                            }), RowIndex
                        );

                        ar.AsyncWaitHandle.WaitOne();
                    }
                } catch (Exception exc) {
                    MessageBox.Show(exc.ToString());
                }
            }
        private void BeginWaitForConnectionCallback(IAsyncResult iar)
        {
            pipeServer = (NamedPipeServerStream)iar.AsyncState;
            pipeServer.EndWaitForConnection(iar);

            if (pipeServer.IsConnected)
                pipeServer.BeginRead(receiveBuffer, 0, receiveBuffer.Length, BeginReadCallback, pipeServer);
        }
Exemple #20
0
        /// <summary>
        /// After the callback, the lock is released
        /// </summary>
        //public void mycallBack(IAsyncResult ar)
        //{
        //    lock (_sync)
        //    {
        //        _server.EndWaitForConnection(ar);
        //        _isLocked = false;
        //    }
        //}
        /// <summary>
        /// Instantiate the server object, along with its reader and writer
        /// Return value: 0 = good, -1 = error
        /// </summary>
        public int start()
        {
            int ret = 0;
            try
            {
                //Create NamedPipe server instance
                _server = new NamedPipeServerStream(Constants.pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                //Wrap pipe in reader/writer (for IO to pipe)
                sw = new StreamWriter(_server);
                sr = new StreamReader(_server);

                //Wait for a connection to the pipe (Asynchronously)
                _server.BeginWaitForConnection((a) =>
                {
                    _server.EndWaitForConnection(a);
                    _isLocked = false;
                }, null);

                //Confirm in debug
                System.Diagnostics.Debug.WriteLine("Connected!");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error creating server NamedPipe" + ex.ToString());
                //Denote that an error occurred
                ret = -1;
            }
            return ret;
        }
        private void ReadMessage(NamedPipeServerStream namedPipeServer)
        {
            var connectEvent = new AutoResetEvent(false);

            var connectResult = namedPipeServer.BeginWaitForConnection(ar => connectEvent.Set(), null);
            WaitHandle.WaitAny(new WaitHandle[] {_cancelConnectionEvent, connectEvent});

            if (_stopReading)
                return;

            namedPipeServer.EndWaitForConnection(connectResult);            

            byte[] data;
            
            using (var ms = new MemoryStream())
            {
                var buffer = new byte[256 * 1024];

                int bytesRead;
                while ((bytesRead = namedPipeServer.Read(buffer, 0, buffer.Length)) > 0)
                    ms.Write(buffer, 0, bytesRead);

                data = ms.ToArray();
            }

            namedPipeServer.Disconnect();

            HandleMessage(data);
        }
        /// <summary>
        /// Background listening thread.
        /// </summary>
        private void OpenPipe()
        {
            while (_running)
            {
                lock (_syncObject)
                {
                    try
                    {
                        _waitingPipe = new NamedPipeServerStream(_endPoint.Name, PipeDirection.InOut, MAX_SERVER_INSTANCES, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

                        _waitingPipe.BeginWaitForConnection(ar =>
                        {
                            try
                            {
                                NamedPipeCommunicationChannel channel;

                                lock (_syncObject)
                                {
                                    _waitingPipe.EndWaitForConnection(ar);
                                    channel = new NamedPipeCommunicationChannel(_endPoint, _waitingPipe);
                                    _waitingPipe = null;
                                }

                                channel.Disconnected += ChannelDisconnected;
                                OnCommunicationChannelConnected(channel);
                            }
                            catch (ObjectDisposedException)
                            { }

                            // listen for next connection
                            if (_running) OpenPipe();
                        }, null);

                        return;
                    }
                    catch
                    {
                        if (_waitingPipe != null)
                        {
                            try
                            {
                                _waitingPipe.Dispose();
                            }
                            catch { }
                            _waitingPipe = null;
                        }
                    }
                }

                if (_running) Thread.Sleep(1000);
            }
        }
Exemple #23
0
        private void doServerWork()
        {
            IsRunning = true;
            serverStream = new NamedPipeServerStream("CWSRestartServer", PipeDirection.InOut, 4, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            Helper.Logging.OnLogMessage("Starting CWSRestartServer for process communication", ServerService.Logging.MessageType.Info);

            while (!_shouldStop)
            {
                wait = new EventWaitHandle(false, EventResetMode.ManualReset);

                serverStream.BeginWaitForConnection(ar =>
                    {
                        try
                        {
                            serverStream.EndWaitForConnection(ar);
                            if (serverStream.IsConnected)
                            {
                                Helper.Logging.OnLogMessage("Module connected", ServerService.Logging.MessageType.Info);
                            }
                            serverStream.Close();
                            wait.WaitOne();
                        }
                        catch (ObjectDisposedException)
                        {
                            Helper.Logging.OnLogMessage("CWSRestartServer has been stopped", ServerService.Logging.MessageType.Info);
                            wait.Set();
                        }
                    }, null);

                wait.WaitOne();
            }

            serverStream.Close();
            IsRunning = false;
        }
Exemple #24
0
        private async Task WriteNamedPipeAsync()
        {
            string pipeID = pID.ToString();

            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("luaPipeW" + pipeID, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
            {
                await Task.Factory.FromAsync((cb, state) => pipeServer.BeginWaitForConnection(cb, state), ar => pipeServer.EndWaitForConnection(ar), null);

                using (StreamWriter pipeWriter = new StreamWriter(pipeServer))
                {
                    pipeWriter.AutoFlush = true;
                    keepWritePipeOpen = true;

                    // Transition to a background thread
                    await TaskScheduler.Default;

                    while (keepWritePipeOpen)
                    {
                        Command command = await this.writeCommandQueue.DequeueAsync();

                        switch (command.Kind)
                        {
                            case CommandKind.Breakpoint:
                                BreakpointCommand bpCommand = command as BreakpointCommand;
                                await pipeWriter.WriteLineAsync("Breakpoint\0");
                                await pipeWriter.WriteLineAsync(bpCommand.File + "\0");
                                await pipeWriter.WriteLineAsync(bpCommand.LineNumber.ToString() + "\0");
                                break;
                            case CommandKind.Step:
                                await pipeWriter.WriteLineAsync("Step\0");
                                break;
                            case CommandKind.Continue:
                                await pipeWriter.WriteLineAsync("Continue\0");
                                break;
                            case CommandKind.Detach:
                                keepWritePipeOpen = false;
                                break;
                            case CommandKind.DebuggerEnvironmentReady:
                                await pipeWriter.WriteLineAsync("DebuggerEnvironmentReady\0");
                                break;
                        }
                    }
                }
            }
        }
Exemple #25
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
        }
Exemple #26
0
            public ServerRunner(String pipeName, Action<string> actionPrimaryReceiveMessage)
            {
                Debug.Assert(pipeName != null);
                Debug.Assert(actionPrimaryReceiveMessage != null);
                for (uint n = 0; n < ServerCount; ++n)
                {
                    _threads[n] = new Thread(() =>
                    {
                        while (!_shutdown)
                        {
                            try
                            { 
                                using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, ServerCount, 
                                    PipeTransmissionMode.Byte, 
                                    PipeOptions.Asynchronous))
                                {
                                    var connectEvent = new AutoResetEvent(false);

                                    // note: unfortunately, WaitForConnection() does not put the current
                                    // thread in an interruptible state. This is based on 
                                    // http://stackoverflow.com/questions/607872 and achieves this
                                    // by using the async version, BeginWaitForConnection, in conjunction
                                    // with an event.
                                    server.BeginWaitForConnection(ar => {
                                        // without this guard, unsafe access to a disposed closure can happen
                                        if (_shutdown) 
                                        {
                                            return;
                                        }

                                        // ReSharper disable AccessToDisposedClosure
                                        Debug.Assert(server != null);                                     
                                        server.EndWaitForConnection(ar);

                                        using (var sr = new StreamReader(server))
                                        {
                                            var line = sr.ReadLine();
                                            if (!_shutdown)
                                            {
                                                // note: there is a small window in which the callback
                                                // is called even though the application is likely no longer
                                                // prepared for it. This needs to be checked for in the callback.
                                                actionPrimaryReceiveMessage(line);
                                            }
                                        }
                                        // ReSharper restore AccessToDisposedClosure
                                        connectEvent.Set();                                      
                                    }, null);

                                    connectEvent.WaitOne();
                                }
                            }
                            catch (IOException xc)
                            {
                                // ignore any IO exceptions happening here. We do not
                                // want to interrupt or crash the primary instance.
                                Console.WriteLine("Ignoring IOException in NamedPipe Server: " + xc.ToString());
                            }
                            catch (ThreadInterruptedException)
                            {
                                return;
                            }
                        }
                    });
                    _threads[n].Start();
                }
            }
Exemple #27
0
        private static void StartCliPipeServer(MainWindow main)
        {
            // http://stackoverflow.com/a/16302188
            Task.Factory.StartNew(() =>
            {
                var server = new NamedPipeServerStream("CliPipe", PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

                var reader = new StreamReader(server);
                var connectedOrWaiting = false;

                while (true)
                {
                    if (!connectedOrWaiting)
                    {
                        server.BeginWaitForConnection((a) => { server.EndWaitForConnection(a); }, null);
                        connectedOrWaiting = true;
                    }

                    if (server.IsConnected)
                    {
                        var line = reader.ReadLine();

                        if (line != null)
                        {
                            // use StartsWith as HyperSpin adds a fullstop to the end (presumably for the rom extension)
                            if (line.StartsWith("-search"))
                            {
                                main.OnTriggerKeyHit(HyperSearchSettings.Instance().Input.Triggers.Search.FirstKey, null);
                            }
                            else if (line.StartsWith("-genre"))
                            {
                                main.OnTriggerKeyHit(HyperSearchSettings.Instance().Input.Triggers.Genre.FirstKey, null);
                            }
                            else if (line.StartsWith("-fav"))
                            {
                                main.OnTriggerKeyHit(HyperSearchSettings.Instance().Input.Triggers.Favourites.FirstKey, null);
                            }
                            else if (line.StartsWith("-settings"))
                            {
                                main.OnTriggerKeyHit(HyperSearchSettings.Instance().Input.Triggers.Settings.FirstKey, null);
                            }
                        }

                        server.Disconnect();
                        connectedOrWaiting = false;
                    }

                    System.Threading.Thread.Sleep(80);
                }
            });
        }