BeginWaitForConnection() public method

public BeginWaitForConnection ( AsyncCallback callback, object state ) : System.IAsyncResult
callback AsyncCallback
state object
return System.IAsyncResult
Beispiel #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!
		}
        private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeServerStream pipeServer = (NamedPipeServerStream) iar.AsyncState;
                // End waiting for the connection
                pipeServer.EndWaitForConnection(iar);

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


                var response = ProccesQueries(sr.ReadLine());
                sw.WriteLine(response);
                sw.Flush();
                pipeServer.WaitForPipeDrain();

                // Kill original sever and create new wait server
                pipeServer.Disconnect();
                pipeServer.Close();
                pipeServer = null;
                pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
                                                       PipeOptions.Asynchronous);

                // Recursively wait for the connection again and again....
                pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, pipeServer);
            }
            catch (Exception e)
            {
                Log.Debug("Pipe server error", e);
            }
        }
Beispiel #3
0
 public PipeServer()
 {
     PipeName = string.Format("exTibiaS{0}", GameClient.Process.Id);
     Pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     OnReceive += new PipeListener(PipeServer_OnReceive);
     Pipe.BeginWaitForConnection(new AsyncCallback(BeginWaitForConnection), null);
 }
Beispiel #4
0
        // Method ====================================================================================
        public void Start(string name)
        {
            pipeName = name;

            isExitThread = false;
            Thread thread = new Thread(() =>
            {
                while (true) {
                    if (isExitThread == true) {
                        isExitThread = false;
                        break;
                    }

                    try {
                        // xp 无法使用pipe,所以加点延迟预防一下...
                        Thread.Sleep(500);
                        NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                        pipeServer.BeginWaitForConnection(ReadCallback, pipeServer);
                    } catch (Exception ex) {
                        Logger.WriteException(ex);
                    }
                }
            });

            thread.IsBackground = true;
            thread.Start();
        }
Beispiel #5
0
 /// <summary>
 ///  Creates a Pipe to interact with an injected DLL or another program.
 /// </summary>
 public Pipe(Client client, string name)
 {
     this.client = client;
     this.name = name;
     pipe = new NamedPipeServerStream(name, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     pipe.BeginWaitForConnection(new AsyncCallback(BeginWaitForConnection), null);
 }
Beispiel #6
0
        private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState;
                // End waiting for the connection
                pipeServer.EndWaitForConnection(iar);
                byte[] buffer = new byte[10000];
                // Read the incoming message
                pipeServer.Read(buffer, 0, 10000);
                // Convert byte buffer to string
                string stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                Debug.WriteLine(stringData + Environment.NewLine);
                // Pass message back to calling form
                PipeMessage.Invoke(stringData);

                // Kill original sever and create new wait server
                pipeServer.Close();
                pipeServer = null;
                pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Recursively wait for the connection again and again....
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch
            {
                return;
            }
        }
        static void NewAccept()
        {
            var stream = new NamedPipeServerStream("Dwarrowdelf.Pipe", PipeDirection.InOut, 4, PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous);

            stream.BeginWaitForConnection(AcceptCallback, stream);
        }
Beispiel #8
0
 private static void CreatePipeListener()
 {
     var pipe = new NamedPipeServerStream("XBEE SAMPLE", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     //var security = pipe.GetAccessControl();
     //security.AddAccessRule(new PipeAccessRule("rob-pc\\rob", PipeAccessRights.FullControl, AccessControlType.Allow));
     //pipe.SetAccessControl(security);
     pipe.BeginWaitForConnection(Pipe_Connected, pipe);
 }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Pipe"/> class.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="name">The name.</param>
 public Pipe(ConnectionProvider connection, string name)
 {
     Connection = connection;
     Name = name;
     Buffer = new byte[1024];
     pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     pipe.BeginWaitForConnection(new AsyncCallback(BeginWaitForConnection), null);
 }
Beispiel #10
0
 private void StartInteropServer()
 {
     if (pipeServer != null)
     {
         pipeServer.Close();
         pipeServer = null;
     }
     pipeServer = new NamedPipeServerStream("SpeditNamedPipeServer", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
     pipeServer.BeginWaitForConnection(new AsyncCallback(PipeConnection_MessageIn), null);
 }
Beispiel #11
0
        public void Start(string pipeName)
        {
            _pipeName = pipeName;

            var security = new PipeSecurity();
            var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            security.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.FullControl, AccessControlType.Allow));
            _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 254,
                PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, security);
            _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, _pipeServer);
            _logger.Info("Opened named pipe '{0}'", _pipeName);
            _closed = false;
        }
        public NamedPipe(string name, string server, IEnumerable<string[]> dataValueArrays)
        {
            _dataValueArrays = dataValueArrays;

              Name = name;
              Server = server;
              Stream = new NamedPipeServerStream(name, PipeDirection.Out, 2, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

              if (Log.IsDebugEnabled)
              {
            Log.DebugFormat("Listening on named pipe {0}", Path);
              }

              Stream.BeginWaitForConnection(OnConnection, this);
        }
Beispiel #13
0
 public PipeServer(string serverName)
 {
     try
     {
         ServerName = serverName;
         _pipe = new NamedPipeServerStream(ServerName, PipeDirection.In, 5, PipeTransmissionMode.Byte,
                                           PipeOptions.Asynchronous);
         _pipe.BeginWaitForConnection(ConnectionHandler, _pipe);
         IsOk = true;
     }
     catch (Exception e)
     {
         IsOk = false;
         Issue = e;
     }
 }
Beispiel #14
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();
     }
 }
        /// <summary>
        /// Start the listening process
        /// </summary>
        /// <param name="source">Name of pipe to be listend to</param>
        public void Listen(string source)
        {

            try
            {
                _pipeName = source;
                var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                //old school style - may want to go async/await in future
                pipeServer.BeginWaitForConnection(new AsyncCallback(ConnectionCallback), pipeServer);

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Beispiel #16
0
        public void Listen(string PipeName)
        {
            try
            {
                // Set to class level var so we can re-use in the async callback method
                _pipeName = PipeName;
                // Create the new async pipe 
                NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Wait for a connection
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception oEX)
            {
                Debug.WriteLine(oEX.Message);
            }
        }
Beispiel #17
0
 public void Init()
 {
     lock (pipeServerLock)
     {
         if (pipeServer != null)
         {
             return;
         }
         var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,
         System.Security.AccessControl.AccessControlType.Allow);
         var sec = new PipeSecurity();
         sec.AddAccessRule(rule);
         pipeServer = new NamedPipeServerStream(HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, sec);
         pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
     }
 }
        private async void ConnectionCallback(IAsyncResult asyncResult)
        {
            try
            {
                using (var pipeServer = asyncResult.AsyncState as NamedPipeServerStream)        // get the pipeserver
                {
                    if (pipeServer != null)
                    {
                        pipeServer.EndWaitForConnection(asyncResult);       // finish connection

                        byte[] buffer = new byte[16 * 1024];
                        using (MemoryStream memoryStream = new MemoryStream())  // create mem stream to read in bytes from pipe stream
                        {
                            int read;
                            while ((read = await pipeServer.ReadAsync(buffer, 0, buffer.Length)) > 0)   // read to the end of the stream
                            {
                                memoryStream.Write(buffer, 0, read);    // write the bytes to memory
                            }

                            var json = GetString(memoryStream.ToArray());                                           // convert bytes to string
                            var msg = Newtonsoft.Json.JsonConvert.DeserializeObject<KioskMessage<object>>(json);   // deserialize to message with object payload - payload will be a json string when <object> is used as generic type
                            var assembly = typeof(KioskMessage<object>).Assembly;                                  // find the assembly where are payload types can be found
                            var dataType = assembly.GetType(msg.DataType);                                          // get the type of the payload
                            var payload = Newtonsoft.Json.JsonConvert.DeserializeObject(msg.Data.ToString(), dataType); // deserialize the payload json to the correct type

                            switch (dataType.FullName)        // brittle switch statements based on type string - better way?
                            {
                                case "KinectPOC.Common.Messages.Demographics":
                                    RaiseDemographicsEvent(payload as DemographicData);
                                    break;
                            }
                        }

                        pipeServer.Close();
                    }
                }

                var newServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                newServer.BeginWaitForConnection(new AsyncCallback(ConnectionCallback), newServer);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Beispiel #19
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);
		}
Beispiel #20
0
        //server
        private void Listen(NamedPipeServerStream server, StreamWriter writer)
        {
            var buffer = new byte[4096];

            #region
            //server.BeginRead(buffer, 0, 4096, p =>
            //{
            //    Trace.WriteLine(p.IsCompleted);
            //    server.EndRead(p);
            //    var reader = new StreamReader(server);
            //    var temp = string.Empty;

            //    while (!string.IsNullOrEmpty((temp = reader.ReadLine())))
            //    {
            //        Trace.WriteLine("Server:from client " + temp);
            //        writer.WriteLine("echo:" + temp);
            //        writer.Flush();
            //        break;
            //    }
            //    server.Disconnect();
            //    Listen(server, writer);
            //}, null);
            #endregion

            server.BeginWaitForConnection(new AsyncCallback(o =>
            {
                var pipe = o.AsyncState as NamedPipeServerStream;
                pipe.EndWaitForConnection(o);

                var reader = new StreamReader(pipe);
                var result = reader.ReadLine();
                var text = string.Format("connected:receive from client {0}|{1}", result.Length, result);
                Trace.WriteLine(text);
                writer.WriteLine(result);
                writer.Flush();
                writer.WriteLine("End");
                writer.Flush();

                server.WaitForPipeDrain();
                server.Disconnect();
                Listen(pipe, writer);
            }), server);
        }
Beispiel #21
0
 public void StartServer(SelectCounter selectCountersDelegate, ReceivedValues receivedValuesDelegate)
 {
     selectCounters = selectCountersDelegate;
     receivedValues = receivedValuesDelegate;
     System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     PipeSecurity ps = new PipeSecurity();
     ps.AddAccessRule(pac);
     sid = null;
     pipeServer = new NamedPipeServerStream(serverPipeName,
             PipeDirection.InOut,
             serverInstances,
             PipeTransmissionMode.Message,
             PipeOptions.Asynchronous,
             1024,
             1024,
             ps);
     AsyncCallback myCallback = new AsyncCallback(AsyncPipeCallback);
     pipeServer.BeginWaitForConnection(myCallback, null);
 }
Beispiel #22
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();
                }
            }
        }
Beispiel #23
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);
       }
     }
       });
 }
Beispiel #25
0
 private void ServerMain()
 {
     while (pipeServer.ThreadState != System.Threading.ThreadState.AbortRequested)
        {
     PipeSecurity security = new PipeSecurity();
     security.AddAccessRule(new PipeAccessRule(
      WindowsIdentity.GetCurrent().User,
      PipeAccessRights.FullControl, AccessControlType.Allow));
     using (NamedPipeServerStream server = new NamedPipeServerStream(instanceID,
      PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
      128, 128, security))
     {
      ServerAsyncInfo async = new ServerAsyncInfo();
      async.Server = server;
      async.WaitHandle = new AutoResetEvent(false);
      IAsyncResult result = server.BeginWaitForConnection(WaitForConnection, async);
      if (result.AsyncWaitHandle.WaitOne())
       async.WaitHandle.WaitOne();
     }
        }
 }
        private async void ConnectionCallback(IAsyncResult asyncResult)
        {
            try
            {
                using (var pipeServer = asyncResult.AsyncState as NamedPipeServerStream)        // get the pipeserver
                {
                    if (pipeServer != null)
                    {
                        pipeServer.EndWaitForConnection(asyncResult);       // finish connection

                        byte[] buffer = new byte[16 * 1024];
                        using (MemoryStream memoryStream = new MemoryStream())  // create mem stream to read in bytes from pipe stream
                        {
                            int read;
                            while ((read = await pipeServer.ReadAsync(buffer, 0, buffer.Length)) > 0)   // read to the end of the stream
                            {
                                memoryStream.Write(buffer, 0, read);    // write the bytes to memory
                            }

                            var json = GetString(memoryStream.ToArray());                                           // convert bytes to string
                            var msg = Newtonsoft.Json.JsonConvert.DeserializeObject<KioskMessage<object>>(json);   // deserialize to message with object payload - payload will be a json string when <object> is used as generic type
                            var assembly = typeof(KioskMessage<object>).Assembly;                                  // find the assembly where are payload types can be found
                            var dataType = assembly.GetType(msg.DataType);                                          // get the type of the payload
                            var payload = Newtonsoft.Json.JsonConvert.DeserializeObject(msg.Data.ToString(), dataType); // deserialize the payload json to the correct type

                            switch (dataType.FullName)        // brittle switch statements based on type string - better way?
                            {
                                case "KinectPOC.Common.Messages.Demographics":

                                    DemographicData demographics = (DemographicData)payload;
                                      
                                    RaiseDemographicsEvent(demographics);

                                    UserExperienceContext uec = new UserExperienceContext();
                                    uec.Age = ((DemographicData)payload).Age;
                                    uec.Gender = ((DemographicData)payload).Gender;
                                    uec.FaceID = ((DemographicData)payload).FaceID;

                                    uec.InteractionCount = 1;
                                   
                                    if(demographics.FaceMatch)
                                    {
                                        //Find out if we've already seen this person
                                        var orginalUser = (from users in _userExperiences where users.FaceID == demographics.FaceID select users).FirstOrDefault();

                                        if (orginalUser == null)
                                        {
                                            uec.TrackingId = demographics.TrackingId;
                                            _userExperiences.Add(uec);
                                        }
                                        else
                                        {
                                            orginalUser.TrackingId = demographics.TrackingId;
                                            orginalUser.InteractionCount++;
                                        }
                                        
                                    }
                                    else
                                    {
                                        uec.TrackingId = demographics.TrackingId;
                                        _userExperiences.Add(uec);
                                    }


                                    
                                    break;
                            }
                        }

                        pipeServer.Close();
                    }
                }

                var newServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                newServer.BeginWaitForConnection(new AsyncCallback(ConnectionCallback), newServer);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Beispiel #27
0
        public void Start(Boolean isClient)
        {
            if (isClient) {
                NamedPipeClientStream client = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                client.Connect(10000); // 10 second timeout.

                pipe = client;
                isReady = true;
            } else {
                // Grant read/write access to everyone, so the pipe can be written to from impersonated processes
                PipeSecurity pipeSecurity = new PipeSecurity();
                pipeSecurity.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                NamedPipeServerStream server = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, pipeSecurity);
                server.BeginWaitForConnection(new AsyncCallback(WaitForConnection), server);
            }
        }
Beispiel #28
0
 //Opens a new pipe to search for clients (other instances of Albedo)
 static void NewPipe()
 {
     server = new NamedPipeServerStream(identifier, PipeDirection.InOut, 5, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     server.BeginWaitForConnection(new AsyncCallback(ClientDetect), null);
     return;
 }
Beispiel #29
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();
                }
            }
Beispiel #30
0
        private void ListenNamedPipe()
        {
            var np = new System.IO.Pipes.NamedPipeServerStream(id.ToString(), System.IO.Pipes.PipeDirection.In, 1, System.IO.Pipes.PipeTransmissionMode.Byte, System.IO.Pipes.PipeOptions.Asynchronous);

            np.BeginWaitForConnection(AsyncCallback, np);
        }
Beispiel #31
-1
        public static void Start()
        {
            if (pipeServer != null)
                throw new InvalidOperationException("Server already started. First call Close.");

            PipeSecurity ps = new PipeSecurity();
            PipeAccessRule par = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            pipeServer = new NamedPipeServerStream(SERVERNAME,
                PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, ps);

            Log.Write("NamedPipeServerStream object created, waiting for client connection...");
            pipeServer.BeginWaitForConnection(onReceive, new object());
        }