WaitForConnection() public méthode

public WaitForConnection ( ) : void
Résultat void
        private static void PipesReader(string pipeName)
        {
            try
            {

                using (var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In))
                {
                    pipeReader.WaitForConnection();
                    WriteLine("reader connected");
                    const int BUFFERSIZE = 256;

                    bool completed = false;
                    while (!completed)
                    {
                        byte[] buffer = new byte[BUFFERSIZE];
                        int nRead = pipeReader.Read(buffer, 0, BUFFERSIZE);
                        string line = Encoding.UTF8.GetString(buffer, 0, nRead);
                        WriteLine(line);
                        if (line == "bye") completed = true;
                    }
                }
                WriteLine("completed reading");
                ReadLine();
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
Exemple #2
0
        private static void ServerThread(object data)
        {
            bool running = true;
            while (running)
            {
                NamedPipeServerStream pipeServer =
                    new NamedPipeServerStream("__MSDN__HELP__PIPE__", PipeDirection.In, 1);
                try
                {
                    pipeServer.WaitForConnection();

                    StreamString ss = new StreamString(pipeServer);

                    string token = ss.ReadString();

                    if (token == "*stop*")
                        running = false;
                    else
                        StringRequest(token);
                }
                catch(Exception)
                {
                }
                finally
                {
                    pipeServer.Close();
                }
            }
        }
Exemple #3
0
        private static void Listen()
        {
            NamedPipeServerStream pipeServer =
                new NamedPipeServerStream(MyPipeName,
                                          PipeDirection.In,
                                          1,
                                          PipeTransmissionMode.Message,
                                          PipeOptions.None);

            StreamReader sr = new StreamReader(pipeServer);

            do
            {
                pipeServer.WaitForConnection();
                string fileName = sr.ReadLine();

                Console.WriteLine(fileName);

                Process proc = new Process();
                proc.StartInfo.FileName = fileName;
                proc.StartInfo.UseShellExecute = true;
                proc.Start();

                pipeServer.Disconnect();
            } while (true);
        }
		private static async void StartGeneralServer()
		{
			Log.Info("Started server");
			var exceptionCount = 0;
			while(exceptionCount < 10)
			{
				try
				{
					using(var pipe = new NamedPipeServerStream("hdtgeneral", PipeDirection.In, 1, PipeTransmissionMode.Message))
					{
						Log.Info("Waiting for connecetion...");
						await Task.Run(() => pipe.WaitForConnection());
						using(var sr = new StreamReader(pipe))
						{
							var line = sr.ReadLine();
							switch(line)
							{
								case "sync":
									HearthStatsManager.SyncAsync(false, true);
									break;
							}
							Log.Info(line);
						}
					}
				}
				catch(Exception ex)
				{
					Log.Error(ex);
					exceptionCount++;
				}
			}
			Log.Info("Closed server. ExceptionCount=" + exceptionCount);
		}
    public static void ClientSendsByteServerReceives()
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
        {
            byte[] sent = new byte[] { 123 };
            byte[] received = new byte[] { 0 };
            Task t = Task.Run(() =>
                {
                    using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out))
                    {
                        client.Connect();
                        Assert.True(client.IsConnected);

                        client.Write(sent, 0, 1);
                    }
                });
            server.WaitForConnection();
            Assert.True(server.IsConnected);

            int bytesReceived = server.Read(received, 0, 1);
            Assert.Equal(1, bytesReceived);

            t.Wait();
            Assert.Equal(sent[0], received[0]);
        }
    }
Exemple #6
0
        public void Start()
        {
            try
            {
                ExtractUpdaterFromResource();

                using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("gsupdater", PipeDirection.Out))
                {
                    ExecuteUpdater();

                    pipeServer.WaitForConnection();

                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine(_sourcePath);
                        sw.WriteLine(_applicationPath);
                    }

                    Environment.Exit(0);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(@"Une erreur s'est produite lors du démarrage de la mise à jour de l'application"
                         + Environment.NewLine
                         + @"Detail du message :"
                         + Environment.NewLine
                         + e.Message);
            }
        }
 private void startServer(object state)
 {
     try
     {
         var pipe = state.ToString();
         using (var server = new NamedPipeServerStream(pipe, PipeDirection.Out))
         {
             server.WaitForConnection();
             while (server.IsConnected)
             {
                 if (_messages.Count == 0)
                 {
                     Thread.Sleep(100);
                     continue;
                 }
                 var bytes = _messages.Pop();
                 var buffer = new byte[bytes.Length + 1];
                 Array.Copy(bytes, buffer, bytes.Length);
                 buffer[buffer.Length - 1] = 0;
                 server.Write(buffer, 0, buffer.Length);
             }
         }
     }
     catch
     {
     }
 }
Exemple #8
0
        public void Run()
        {
            while (true)
            {
                NamedPipeServerStream pipeStream = null;
                try
                {
                    pipeStream = new NamedPipeServerStream(ConnectionName, PipeDirection.InOut, -1, PipeTransmissionMode.Message);
                    pipeStream.WaitForConnection();
                    if (_stop)
                        return;

                    // Spawn a new thread for each request and continue waiting
                    var t = new Thread(ProcessClientThread);
                    t.Start(pipeStream);
                }
                catch (Exception)
                {
                    if (pipeStream != null)
                        pipeStream.Dispose();
                    throw;
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }
        public void Run()
        {
            while (true)
            {
                var security = new PipeSecurity();
                security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow));

                using (pipeServer = new NamedPipeServerStream(
                    Config.PipeName,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.None,
                    Config.BufferSize, Config.BufferSize,
                    security,
                    HandleInheritability.None
                    ))
                {
                    try
                    {
                        Console.Write("Waiting...");
                        pipeServer.WaitForConnection();
                        Console.WriteLine("...Connected!");

                        if (THROTTLE_TIMER)
                        {
                            timer = new Timer
                            {
                                Interval = THROTTLE_DELAY,
                            };
                            timer.Elapsed += (sender, args) => SendMessage();
                            timer.Start();

                            while(pipeServer.IsConnected)Thread.Sleep(1);
                            timer.Stop();
                        }
                        else
                        {
                            while (true) SendMessage();
                        }
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                    finally
                    {
                        if (pipeServer != null)
                        {
                            Console.WriteLine("Cleaning up pipe server...");
                            pipeServer.Disconnect();
                            pipeServer.Close();
                            pipeServer = null;
                        }
                    }

                }

            }
        }
        public virtual async void OnAttachServer(NamedPipeServerStream server)
        {
            await Task.Run(() => server.WaitForConnection()); //偷懒

            using (StreamReader reader = new StreamReader(server))
            {
                using (StreamWriter writer = new StreamWriter(server))
                {
                    _pipes.Add(server, new KeyValuePair<StreamReader, StreamWriter>(reader, writer));
                    while (server.IsConnected)
                    {
                        try
                        {
                            var req = JsonConvert.DeserializeObject<NewTaskRequest>(reader.ReadLine());
                            TimePlan plan = new TimePlan(req.Describe, req.leftTime);
                            _callbackPipe.Add(plan, server);
                            plan.TimePlanExpired +=
                                (sender, args) =>
                                    _pipes[_callbackPipe[args.CurrentPlan]].Value?.Write(
                                        new TaskCompletePostBack(args.CurrentPlan.Description, args.CurrentPlan.EndTime));
                            _timePlans.AddSafe(plan);
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    }
                    _pipes.Remove(server);
                }
            }
        }
Exemple #11
0
        private void UserSignIn(string username, string password)
        {
            string hashed_password = sha256(password);
            MessageBox.Show(hashed_password);
            //send username and password to python and checks if correct
            string info = username + "#" + hashed_password;
            // Open the named pipe.

            var server = new NamedPipeServerStream("Communicate");
            server.WaitForConnection();     
            var br = new BinaryReader(server);
            var bw = new BinaryWriter(server); 
            send(bw, info);
            string message = recv(br); 
            server.Close();
            server.Dispose();

            //if receives true then send the user to the next gui.
            if (message == "1")
            {
                
                SaveFile form = new SaveFile();
                form.Show();

            }
            else
            {
                
                MessageBox.Show("incorrect password or username");
                this.Show();
            }
            
            
        }
Exemple #12
0
		static void IPCThread()
		{
			string pipeName = string.Format("bizhawk-pid-{0}-IPCKeyInput", System.Diagnostics.Process.GetCurrentProcess().Id);


			for (; ; )
			{
				using (NamedPipeServerStream pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024))
				{
					try
					{
						pipe.WaitForConnection();

						BinaryReader br = new BinaryReader(pipe);

						for (; ; )
						{
							int e = br.ReadInt32();
							bool pressed = (e & 0x80000000) != 0;
							lock (PendingEventList)
								PendingEventList.Add(new KeyInput.KeyEvent { Key = (Key)(e & 0x7FFFFFFF), Pressed = pressed });
						}
					}
					catch { }
				}
			}
		}
        public void Worker()
        {
            while (true)
            {
                try
                {
                    var serverStream = new NamedPipeServerStream("YetAnotherRelogger", PipeDirection.InOut, 100, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

                    serverStream.WaitForConnection();

                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        using (var pipeClientConnection = (NamedPipeServerStream)state)
                        {
                            var handleClient = new HandleClient(pipeClientConnection);
                            handleClient.Start();
                        }
                    }, serverStream);
                }
                catch (Exception ex)
                {
                    Logger.Instance.WriteGlobal(ex.Message);
                }
                Thread.Sleep(Program.Sleeptime);
            }
        }
Exemple #14
0
        private void LaunchServer(string pipeName)
        {
            try
            {
                Console.WriteLine("Creating server: " + pipeName);
                server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 4);
                Console.WriteLine("Waiting for connection");
                server.WaitForConnection();
                reader = new StreamReader(server);

                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Begin server read loop");
                    while (true)
                    {
                        try
                        {
                            var line = reader.ReadLine();
                            messages.Enqueue(line);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("ServerLoop exception: {0}", ex.Message);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("LaunchServer exception: {0}", ex.Message);
            }
        }
Exemple #15
0
 private void ListenForArguments(object state)
 {
     try
     {
         using (NamedPipeServerStream stream = new NamedPipeServerStream(this.identifier.ToString()))
         {
             using (StreamReader reader = new StreamReader(stream))
             {
                 stream.WaitForConnection();
                 List<string> list = new List<string>();
                 while (stream.IsConnected)
                 {
                     list.Add(reader.ReadLine());
                 }
                 ThreadPool.QueueUserWorkItem(new WaitCallback(this.CallOnArgumentsReceived), list.ToArray());
             }
         }
     }
     catch (IOException)
     {
     }
     finally
     {
         this.ListenForArguments(null);
     }
 }
        /// <summary>
        /// Listens for arguments on a named pipe.
        /// </summary>
        /// <param name="state">State object required by WaitCallback delegate.</param>
        private void ListenForArguments(Object state)
        {
            try
            {
                using (NamedPipeServerStream server = new NamedPipeServerStream(identifier.ToString()))
                using (StreamReader reader = new StreamReader(server))
                {
                    server.WaitForConnection();
                    List<String> arguments = new List<String>();
                    while (server.IsConnected)
                    {
                        string line = reader.ReadLine();
                        if (line != null && line.Length > 0)
                        {
                            arguments.Add(line);
                        }
                    }

                    ThreadPool.QueueUserWorkItem(new WaitCallback(CallOnArgumentsReceived), arguments.ToArray());
                }
            }
            catch (IOException)
            { } //Pipe was broken
            finally
            {
                ListenForArguments(null);
            }
        }
Exemple #17
0
 public void Intercept(IInvocation invocation)
 {
     var pipename = Guid.NewGuid().ToString();
     var procArgs = new List<string> {
         Quote(invocation.TargetType.AssemblyQualifiedName),
         Quote(invocation.MethodInvocationTarget.Name),
         pipename,
     };
     procArgs.AddRange(invocation.Arguments.Select(a => Serialize(a)));
     var proc = new Process {
         StartInfo = {
             FileName = "runner.exe",
             Arguments = String.Join(" ", procArgs.ToArray()),
             UseShellExecute = false,
             CreateNoWindow = true,
         }
     };
     using (var pipe = new NamedPipeServerStream(pipename, PipeDirection.In)) {
         proc.Start();
         pipe.WaitForConnection();
         var r = bf.Deserialize(pipe);
         r = r.GetType().GetProperty("Value").GetValue(r, null);
         proc.WaitForExit();
         if (proc.ExitCode == 0) {
             invocation.ReturnValue = r;
         } else {
             var ex = (Exception) r;
             throw new Exception("Error in external process", ex);
         }
     }
 }
Exemple #18
0
        static void ConnectPythonPipe(NamedPipeServerStream server)
        {

            Console.WriteLine("Waiting for connection to Python...");
            server.WaitForConnection();
            Console.WriteLine("Connected to Python.");
        }
Exemple #19
0
		public void Get(Stream s)
		{
			if (thr != null)
				throw new InvalidOperationException("Can only serve one thing at a time!");
			if (e != null)
				throw new InvalidOperationException("Previous attempt failed!", e);
			if (!s.CanWrite)
				throw new ArgumentException("Stream must be readable!");

			using (var evt = new ManualResetEventSlim())
			{
				thr = new Thread(delegate()
					{
						try
						{
							using (var srv = new NamedPipeServerStream(PipeName, PipeDirection.In))
							{
								evt.Set();
								srv.WaitForConnection();
								srv.CopyTo(s);
								//srv.Flush();
							}
						}
						catch (Exception ee)
						{
							e = ee;
						}
					});
				thr.Start();
				evt.Wait();
			}
		}
Exemple #20
0
    private void server()
    {
        System.IO.Pipes.NamedPipeServerStream pipeServer = new System.IO.Pipes.NamedPipeServerStream("testpipe", System.IO.Pipes.PipeDirection.InOut, 4);

        StreamReader sr = new StreamReader(pipeServer);
        StreamWriter sw = new StreamWriter(pipeServer);

        do
        {
            try
            {
                pipeServer.WaitForConnection();
                string test;
                sw.WriteLine("Waiting");
                sw.Flush();
                pipeServer.WaitForPipeDrain();
                test = sr.ReadLine();
                Console.WriteLine(test);
            }

            catch (Exception ex)
            { throw ex; }

            finally
            {
                pipeServer.WaitForPipeDrain();
                if (pipeServer.IsConnected)
                {
                    pipeServer.Disconnect();
                }
            }
        } while (true);
    }
        private static void PipesReader2(string pipeName)
        {
            try
            {

                var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In);
                using (var reader = new StreamReader(pipeReader))
                {
                    pipeReader.WaitForConnection();
                    WriteLine("reader connected");

                    bool completed = false;
                    while (!completed)
                    {
                        string line = reader.ReadLine();
                        WriteLine(line);
                        if (line == "bye") completed = true;
                    }
                }
                WriteLine("completed reading");
                ReadLine();
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
Exemple #22
0
        private static void StartServer(Type interfaceType, Type implType, string pipeName)
        {
            //create the server
            var controller = new RpcController();
            
            var server = new RpcServer(controller);

            //register the service with the server. We must specify the interface explicitly since we did not use attributes
            server.GetType()
                  .GetMethod("RegisterService")
                  .MakeGenericMethod(interfaceType)
                  .Invoke(server, new[] {Activator.CreateInstance(implType)});

            //build the connection using named pipes
            try
            {
                pipeServerStreamIn = CreateNamedPipe(pipeName + "ctos", PipeDirection.In);
                pipeServerStreamOut = CreateNamedPipe(pipeName + "stoc", PipeDirection.Out);
                streamsCreated = true;
                pipeServerStreamIn.WaitForConnection();
                pipeServerStreamOut.WaitForConnection();
                
                //create and start the channel which will receive requests
                var channel = new StreamRpcChannel(controller, pipeServerStreamIn, pipeServerStreamOut, useSharedMemory: true);
                channel.Start();
            }
            catch (IOException e)
            {
                //swallow and exit
                Console.WriteLine("Something went wrong (pipes busy?), quitting: " + e);
                throw;
            }
        }
		private static async void StartImportServer()
		{
			Log.Info("Started server");
			var exceptionCount = 0;
			while(exceptionCount < 10)
			{
				try
				{
					using(var pipe = new NamedPipeServerStream("hdtimport", PipeDirection.In, 1, PipeTransmissionMode.Message))
					{
						Log.Info("Waiting for connecetion...");
						await Task.Run(() => pipe.WaitForConnection());
						using(var sr = new StreamReader(pipe))
						{
							var line = sr.ReadLine();
							var decks = JsonConvert.DeserializeObject<JsonDecksWrapper>(line);
							decks.SaveDecks();
							Log.Info(line);
						}
					}
				}
				catch(Exception ex)
				{
					Log.Error(ex);
					exceptionCount++;
				}
			}
			Log.Info("Closed server. ExceptionCount=" + exceptionCount);
		}
        private void CreatePipeServer()
        {
            pipeServer = new NamedPipeServerStream("www.pmuniverse.net-installer", PipeDirection.InOut, 1, (PipeTransmissionMode)0, PipeOptions.Asynchronous);

            pipeServer.WaitForConnection();
            //pipeServer.BeginWaitForConnection(new AsyncCallback(PipeConnected), pipeServer);

            Pipes.StreamString streamString = new Pipes.StreamString(pipeServer);

            while (pipeServer.IsConnected) {
                string line = streamString.ReadString();

                if (!string.IsNullOrEmpty(line)) {

                    if (line.StartsWith("[Status]")) {
                        installPage.UpdateStatus(line.Substring("[Status]".Length));
                    } else if (line.StartsWith("[Progress]")) {
                        installPage.UpdateProgress(line.Substring("[Progress]".Length).ToInt());
                    } else if (line.StartsWith("[Component]")) {
                        installPage.UpdateCurrentComponent(line.Substring("[Component]".Length));
                    } else if (line == "[Error]") {
                        throw new Exception(line.Substring("[Error]".Length));
                    } else if (line == "[InstallComplete]") {
                        installPage.InstallComplete();
                        break;
                    }

                }
            }

            pipeServer.Close();
        }
Exemple #25
0
    static public async Task WaitForConnectionAsync(this System.IO.Pipes.NamedPipeServerStream self, CancellationToken token)
    {
        Exception err = null;
        var       cts = new CancellationTokenSource();
        Thread    t   = new Thread(delegate()
        {
            try
            {
                self.WaitForConnection();
            }
            catch (Exception x)
            {
                err = x;
                cts.Cancel();
            }
        });

        try
        {
            await Task.Delay(-1, cts.Token);
        }
        catch (Exception)
        {
        }
        if (err != null)
        {
            throw new Exception(err.Message, err);
        }
    }
        static void Main()
        {
            using (var pipeServer =
                      new NamedPipeServerStream("testpipe", PipeDirection.Out))
            {
                try
                {
                    Console.WriteLine("NamedPipeServerStream object created.");

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

                    Console.WriteLine("Client connected.");

                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        while (true)
                        {
                            Console.Write("Enter text: ");
                            sw.WriteLine(Console.ReadLine());
                        }
                    }

                }
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);

                }

            }
        }
Exemple #27
0
        private static void PipeServer()
        {
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("BerkeleyDbWebApiSelfHost", PipeDirection.In))
                pipeServer.WaitForConnection();

            IntPtr stdin = GetStdHandle(StdHandle.Stdin);
            CloseHandle(stdin);
        }
Exemple #28
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                port = new SerialPort("COM5", 9600);
            }
            else
            {
                port = new SerialPort(args[0], 9600);
            }
            var pipein = new NamedPipeServerStream("KTANEin");
            var morsepipeout = new NamedPipeClientStream("KTANEMorseOut");
            var pipeout = new NamedPipeClientStream("KTANEout");
            pipein.WaitForConnection();
            Thread.Sleep(1000);
            pipeout.Connect();
            morsepipeout.Connect();
            Console.WriteLine("pipes open");
            StreamReader reader = new StreamReader(pipeout);
            StreamReader MorseReader = new StreamReader(morsepipeout);
            StreamWriter writer = new StreamWriter(pipein);
            writer.AutoFlush = true;

            port.Open();

            Thread morseThread = new Thread(new ParameterizedThreadStart(MorseHandler));
            morseThread.Start(MorseReader);
            while (true)
            {
                string hardwareInput = port.ReadLine();
                Console.WriteLine("Hardware "+hardwareInput);
                writer.WriteLine(hardwareInput);

                string inputraw = reader.ReadLine().ToLower();
                switch (inputraw)
                {
                    case "true":
                        inputraw = "1";
                        break;
                    case "false":
                        inputraw = "0";
                        break;
                }

                byte result = Convert.ToByte(Int32.Parse(inputraw));
                Console.WriteLine("Response " + result);

                port.Write(new byte[]{result},0,1);

                string isDetonated = reader.ReadLine().ToLower();
                isDetonated = reader.ReadLine().ToLower();//what the f**k is happening
                if (isDetonated.Equals("detonated:true"))
                {
                    Console.WriteLine("Explosion");
                    port.Write(new byte[] { 253 }, 0, 1);
                }
            }
        }
Exemple #29
0
        private void PipeThreadStart()
        {
            PipeSecurity pSec = new PipeSecurity();
            PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
            , PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);
            pSec.AddAccessRule(pAccRule);

            using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Byte,
                PipeOptions.None,
                MAX_STRING_CCH * 2,
                MAX_STRING_CCH * 2,
                pSec,
                HandleInheritability.Inheritable))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("(pipe thread) Waiting for connection...");
                Console.ForegroundColor = ConsoleColor.Gray;

                try
                {
                    _pipeServer.WaitForConnection();

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("(pipe thread) Client connected.");
                    Console.ForegroundColor = ConsoleColor.Gray;

                    while (true)
                    {
                        byte[] readBuf = new byte[MAX_STRING_CCH * 2];

                        int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);

                        string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);

                        Console.WriteLine(str);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("--------------------------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (_blockQuery)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("(pipe thread) QUERY ABORTED");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }

                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
                }
            }
        }
Exemple #30
0
        private void UserSignIn(string username, string password)
        {
            if (username == "")
            {
                MessageBox.Show("Please enter username");
                this.Show();
            }
            else if(password == "")
            {
                MessageBox.Show("Please enter password");
                this.Show();
            }
            else
            {

                string hashed_password = sha256(password);
                //send username and password to python and checks if correct
                string info = "login#" + username + "#" + hashed_password;
                // Open the named pipe.

                var server = new NamedPipeServerStream("Communicate");
                server.WaitForConnection();     
                var br = new BinaryReader(server);
                var bw = new BinaryWriter(server); 
                send(bw, info);
                string message_to_split = recv(br);
                message_to_split = message_to_split + recv(br);
                string message = message_to_split.Split('#')[0];
                if (message_to_split.Split('#')[1] != "0")
                {
                    this.my_uid = message_to_split.Split('#')[2];
                    this.firstname = message_to_split.Split('#')[1];
                    this.lastname = message_to_split.Split('#')[3];
                    MessageBox.Show(my_uid + firstname + lastname);
                }
                server.Close();
                server.Dispose();
                
                //if receives true then send the user to the next gui.
                if (message == "Signed in")
                {
                    string user_info = this.my_uid + "#" + this.firstname + "#" + this.lastname;
                    SaveFile form = new SaveFile(user_info);
                    form.Show();
                }
                else
                {
                
                    MessageBox.Show("incorrect password or username");
                    this.Show();
                }
            
            
            
            }
        }
 public PipeJunction(string pipeName)
 {
     // The blocking synchronous way of using it is used here because there is a bug in mono
     // the PipeOptions enum does not have the correct int values compared to ms .net version
     _server = new NamedPipeServerStream(pipeName, PipeDirection.Out);
     var connect = new Thread(() => _server.WaitForConnection());
     _pipes.Add(connect);
     _serverThread = new Thread(startServer);
     connect.Start();
     _serverThread.Start();
 }
        void PipeThread()
        {
            NamedPipeServerStream pipeServer = null;
            try
            {
                pipeServer = new NamedPipeServerStream("NowPlayingtunesSongPipe", PipeDirection.InOut);
                pipeServer.WaitForConnection();
                //When Connected
                StreamString stream = new StreamString(pipeServer);
                String playerStr = stream.ReadString();
                Debug.WriteLine("[foobar2000]Song changed.");
                Debug.WriteLine(playerStr);
                Debug.WriteLine("[foobar2000]dump end.");
                String[] playerStrSplit = playerStr.Split('\n');
                Core.iTunesClass song = new Core.iTunesClass();
                song.AlbumArtworkEnabled = false;
                song.SongTitle = playerStrSplit[0];
                song.SongAlbum = playerStrSplit[1];
                song.SongArtist = playerStrSplit[2];
                song.SongAlbumArtist = playerStrSplit[3];
                song.isFoobar = true;
                try
                {
                    song.SongTrackNumber = int.Parse(playerStrSplit[4]);
                }
                catch (Exception ex2)
                {
                }
                song.SongGenre = playerStrSplit[5];
                song.SongComposer = playerStrSplit[6];

                pipeServer.Close();
                pipeServer.Dispose();
                //適当にイベント発生させる
                onSongChangedEvent(song);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[foobar2000] ERROR");
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                    {
                        pipeServer.Dispose();
                    }
                }
            }
            //Remake thread
            StartThread();
        }