Connect() public method

public Connect ( ) : void
return void
示例#1
0
 public static void SendMessage(String optionVal)
 {
     using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RipplePipe", PipeDirection.Out, PipeOptions.Asynchronous))
     {
         try
         {
             pipeClient.Connect(2000);
         }
         catch (Exception)
         {
             //Try once more
             try
             {
                 pipeClient.Connect(5000);
             }
             catch (Exception)
             {
                 return;
             }
         }
         //Connected to the server or floor application
         using (StreamWriter sw = new StreamWriter(pipeClient))
         {
             sw.Write(optionVal);
         }
     }
 }
示例#2
0
        public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
        {
            _targetServer = serverName;
            _callbackObject = callbackObject;
            _writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
            _writeTaskFactory = new TaskFactory(_writeScheduler);

            try
            {
                _pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.WriteThrough, Security.Principal.TokenImpersonationLevel.None);

                bool isInfiniteTimeOut = long.MaxValue == timerExpire;
                if (isInfiniteTimeOut)
                {
                    _pipeStream.Connect(Threading.Timeout.Infinite);
                }
                else
                {
                    TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
                    ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;

                    _pipeStream.Connect((int)ts.TotalMilliseconds);
                }
            }
            catch(TimeoutException te)
            {
                SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnTimeoutError, te);
                _status = TdsEnums.SNI_WAIT_TIMEOUT;
                return;
            }
            catch(IOException ioe)
            {
                SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
                _status = TdsEnums.SNI_ERROR;
                return;
            }

            if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
            {
                SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
                _status = TdsEnums.SNI_ERROR;
                return;
            }

            _sslOverTdsStream = new SslOverTdsStream(_pipeStream);
            _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

            _stream = _pipeStream;
            _status = TdsEnums.SNI_SUCCESS;
        }
示例#3
0
 public static void SendBreakRequest()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) {
         client.Connect();
         client.Write(BREAK, 0, BREAK.Length);
     }
 }
示例#4
0
        static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                return 1;
            }

            var pipeName = args[0];

            //Console.WriteLine(nameof(pipeName) + " = " + pipeName);

            using (var pipeClient = new NamedPipeClientStream(pipeName))
            {
                pipeClient.Connect();

                // Receive meta data first.
                var messageTypeCommunicator = new CodeShardCommunicator<Type>(pipeClient);
                var messageType = messageTypeCommunicator.Receive();
                var entryPointCommunicator = new CodeShardCommunicator<object>(pipeClient);
                var entryPointInstance = entryPointCommunicator.Receive();

                // Get run method for the hosted user code.
                var entryPointType = entryPointInstance.GetType();
                var expectedInterfaceType = typeof(ICodeShardEntryPoint<>).MakeGenericType(messageType);
                var runMethodInfo = expectedInterfaceType.GetMethods()[0];

                // Create communicator instance for the hosted user code.
                var communicatorType = typeof(CodeShardCommunicator<>).MakeGenericType(messageType);
                var communicatorInstance = Activator.CreateInstance(communicatorType, pipeClient);

                runMethodInfo.Invoke(entryPointInstance, new object[] { communicatorInstance });
            }

            return 0;
        }
示例#5
0
        public DxDeviceCtrl()
        {
            KeybdPipeSwCollection=new Collection<StreamWriter>();

            var id = 0;
            bool failed = false;
            for (id = 0; false == failed; ++id)
            {
                var KeybdPipe = new NamedPipeClientStream(".", "DxKeybdPipe" + id.ToString(), PipeDirection.Out);
                try
                {
                    KeybdPipe.Connect(50);
                    if (true == KeybdPipe.IsConnected)
                    {
                        var KeybdPipeSW = new StreamWriter(KeybdPipe);
                        KeybdPipeSW.AutoFlush = true;
                        KeybdPipeSwCollection.Add(KeybdPipeSW);
                    }
                    else
                    {
                        failed = true;
                    }
                }
                catch (Exception )
                {
                    failed = true;
                }
            }
        }
        private static void PipesWriter(string pipeName)
        {
            try
            {
                using (var pipeWriter = new NamedPipeClientStream("TheRocks", pipeName, PipeDirection.Out))
                {
                    pipeWriter.Connect();
                    WriteLine("writer connected");

                    bool completed = false;
                    while (!completed)
                    {
                        string input = ReadLine();
                        if (input == "bye") completed = true;

                        byte[] buffer = Encoding.UTF8.GetBytes(input);
                        pipeWriter.Write(buffer, 0, buffer.Length);
                    }
                }
                WriteLine("completed writing");
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
示例#7
0
        public void Connect(string pipeName, string serverName = ".", int timeout = 2000)
        {
            NamedPipeClientStream pipeStream = null;

            try
            {
                pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut,
                                                       PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation);
                pipeStream.Connect(timeout);
                using (var stringStream = new StringStream(pipeStream))
                {
                    if (OnConnected != null)
                    {
                        OnConnected(stringStream);
                    }
                }
            }
            catch (Exception exception)
            {
                if (OnErrorOcurred != null)
                {
                    OnErrorOcurred(exception);
                }
            }
            finally
            {
                if (pipeStream != null && pipeStream.IsConnected)
                {
                    pipeStream.Flush();
                    pipeStream.Close();
                }
            }
        }
示例#8
0
        public void ThreadStartClient(object obj)
        {
            // Ensure that we only start the client after the server has created the pipe
            ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

            // Only continue after the server was created -- otherwise we just fail badly
            // SyncClientServer.WaitOne();

            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(pipeName))
            {
                // The connect function will indefinately wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                pipeStream.Connect(5000);

                //Console.WriteLine("[Client] Pipe connection established");
                using (StreamWriter sw = new StreamWriter(pipeStream))
                {
                    ////sw.AutoFlush = true;
                    if (Environment.GetCommandLineArgs().Length >= 2)
                    {
                        string fname = Environment.GetCommandLineArgs()[1];
                        sw.WriteLine(fname);
                        sw.Flush();
                    }
                }
            }
        }       
示例#9
0
        public void Close()
        {
            Console.WriteLine(string.Format("closing pipe server {0}...", PipeName));
            m_closing = true;
            //emulate new client connected to resume listener thread
            using (NamedPipeClientStream fakeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
            {
                try
                {
                    fakeClient.Connect(100);
                    fakeClient.Close();
                }
                catch
                {
                    //server was stopped already
                }
            }
            if (m_listenerThread != null && m_listenerThread.IsAlive)
            {
                if (!m_listenerThread.Join(5000))
                {
                    m_listenerThread.Abort();
                }
            }
            m_listenerThread = null;

            Console.WriteLine(string.Format("disconnecting clients from pipe {0}...", PipeName));
            while (m_pipeStreams.Count > 0)
            {
                DisconnectClient(m_pipeStreams[0]);
            }

            Console.WriteLine(string.Format("Pipe server {0} stopped OK", PipeName));
        }
        /// <summary>
        /// Calls method with one parameter and result. Deserializes parameter and serialize result.
        /// </summary>
        /// <param name="type">Type containing method</param>
        /// <param name="methodName">Name of method to call</param>
        /// <param name="pipeName">Name of pipe to pass parameter and result</param>
        static void InvokeFunc(Type type, string methodName, string pipeName)
        {
            using (var pipe = new NamedPipeClientStream(pipeName))
            {

                pipe.Connect();

                var formatter = new BinaryFormatter();
                ProcessThreadParams pars;
                var lengthBytes = new byte[4];
                pipe.Read(lengthBytes, 0, 4);
                var length = BitConverter.ToInt32(lengthBytes, 0);

                var inmemory = new MemoryStream(length);
                var buf = new byte[1024];
                while (length != 0)
                {
                    var red = pipe.Read(buf, 0, buf.Length);
                    inmemory.Write(buf, 0, red);
                    length -= red;
                }
                inmemory.Position = 0;
                try
                {
                    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                      {
                          return type.Assembly;
                      };

                    pars = (ProcessThreadParams)formatter.Deserialize(inmemory);

                    var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
                    if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);

                    if (pars.Pipe != null)
                    {
                        var auxPipe = new NamedPipeClientStream(pars.Pipe);
                        auxPipe.Connect();

                        for (int i = 0; i < pars.Parameters.Length; i++)
                            if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
                    }
                    object result = method.Invoke(pars.Target, pars.Parameters);

                    var outmemory = new MemoryStream();
                    formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
                    outmemory.WriteTo(pipe);
                }
                catch (TargetInvocationException e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
                    throw e.InnerException;
                }
                catch (Exception e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
                    throw;
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedPipeCommunicationChannel" /> class.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        /// <param name="pipeStream">An existing pipe stream or <c>null</c> to create client.</param>
        public NamedPipeCommunicationChannel(NamedPipeEndPoint endPoint, PipeStream pipeStream = null)
        {
            _endPoint = endPoint;

            if (pipeStream != null) _pipeStream = pipeStream;
            else
            {
                var client = new NamedPipeClientStream(".", endPoint.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

                // connect overload with timeout is extremely processor intensive
                int elapsed = 0, connectionTimeout = endPoint.ConnectionTimeout * 1000;

            CONNECT:
                try
                {
                    client.Connect(0);
                }
                catch (TimeoutException)
                {
                    Thread.Sleep(CONNECT_ATTEMPT_INTERVAL_MS);

                    if (endPoint.ConnectionTimeout != Timeout.Infinite && (elapsed += CONNECT_ATTEMPT_INTERVAL_MS) > connectionTimeout)
                        throw new TimeoutException("The host failed to connect. Timeout occurred.");

                    goto CONNECT;
                }

                _pipeStream = client;
            }

            _buffer = new byte[ReceiveBufferSize];
            _syncLock = new object();
        }
示例#12
0
 public MouseCtrl()
 {
     var npipe = new NamedPipeClientStream(".", "mGetCursorPosServerPipe0", PipeDirection.Out);
     npipe.Connect();
     MousePosPipeSW = new StreamWriter(npipe);
     MousePosPipeSW.AutoFlush = true;
 }
示例#13
0
        void process(object o)
        {
            try
            {
                using (NamedPipeClientStream pipeClient =
                       new NamedPipeClientStream(".", "testpipe", PipeDirection.In))
                {
                    // Connect to the pipe or wait until the pipe is available.
                    Console.Write("Attempting to connect to pipe...");
                    pipeClient.Connect();

                    Console.WriteLine("Connected to pipe.");
                    Console.WriteLine("There are currently {0} pipe server instances open.",
                       pipeClient.NumberOfServerInstances);

                    using (StreamReader sr = new StreamReader(pipeClient))
                    {
                        // Display the read text to the console
                        string temp;

                        while (true)
                        {
                            if ((temp = sr.ReadLine()) != null)
                            {
                                Console.WriteLine("Received from server: {0}", temp);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
示例#14
0
        public string Send(string sendStr, string pipeName, int timeOut = 1000)
        {
            try
            {
                NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);

                pipeStream.Connect(timeOut);


                var sr = new StreamReader(pipeStream);
                var sw = new StreamWriter(pipeStream);
                 

                sw.WriteLine(sendStr);
                sw.Flush();

                string temp = sr.ReadToEnd();
                return temp;
            }
            catch (Exception oEX)
            {
                MessageBox.Show("Error :" + oEX.Message);
                Debug.WriteLine(oEX.Message);
            }
            return "";
        }
示例#15
0
        public static List<Server> GetActiveServerList()
        {
            List<Server> serverList = new List<Server>();
            List<int> pids = new List<int>();

            foreach (Process p in Process.GetProcessesByName(ServerName))
            {
                pids.Add(p.Id);
            }

            foreach (int pid in pids)
            {
                using (NamedPipeClientStream npc = new NamedPipeClientStream(".", "wss" + pid, PipeDirection.In))
                {
                    try
                    {
                        npc.Connect(1500);
                        using (StreamReader sr = new StreamReader(npc))
                        {
                            string data = sr.ReadToEnd();
                            string[] chunks = data.Split(':');
                            if (chunks.Length != 2) continue;
                            serverList.Add(new Server() { Name = chunks[0], Port = int.Parse(chunks[1]), Pid = pid });
                        }
                    }
                    catch (TimeoutException)
                    {
                        continue; // Since this one timed out, we don't care about it, so move on to the next one.
                    }
                }
            }

            return serverList;
        }
示例#16
0
 private void ensureOnlyOne()
 {
     var pipeName = $"{this.GetType().FullName}.{winServiceInstaller.ServiceName}";
     try
     {
         var serverStream = createNewNamedPipedServerStream(pipeName);
         AsyncCallback ac = null;
         ac = ar =>
         {
             showForm();
             serverStream.Close();
             serverStream = createNewNamedPipedServerStream(pipeName);
             serverStream.BeginWaitForConnection(ac, null);
         };
         serverStream.BeginWaitForConnection(ac, null);
     }
     catch
     {
         try
         {
             var clientStream = new NamedPipeClientStream(pipeName);
             clientStream.Connect();
             clientStream.Close();
         }
         finally
         {
             this.DialogResult = DialogResult.Cancel;
             this.Close();
             Environment.Exit(0);
         }
     }
 }
示例#17
0
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var p = UtilityProgram.CallWithAdmin("--download-packages", mod);
            Regex r = new Regex(@"(\d{1,3})% (\d+/\d+ bytes)");

            NamedPipeClientStream pipe = new NamedPipeClientStream(".", "OpenRA.Utility", PipeDirection.In);
            pipe.Connect();

            using (var response = new StreamReader(pipe))
            {
                while (!p.HasExited)
                {
                    string s = response.ReadLine();
                    if (Util.IsError(ref s))
                    {
                        e.Cancel = true;
                        e.Result = s;
                        return;
                    }
                    if (!r.IsMatch(s)) continue;
                    var m = r.Match(s);
                    backgroundWorker1.ReportProgress(int.Parse(m.Groups[1].Value), m.Groups[2].Value);
                }
            }
        }
        private void Run()
        {
            foreach (var message in _messages.GetConsumingEnumerable())
            {
                try
                {
                    var pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out, PipeOptions.Asynchronous);

                    try
                    {
                        pipe.Connect(0);
                    }
                    catch (TimeoutException)
                    {
                        continue;
                    }

                    using (var writer = new StreamWriter(pipe))
                    {
                        writer.WriteLine(message);
                    }
                }
                catch (Exception ex)
                {
                    // TODO: Something?
                    continue;
                }
            }
        }
示例#19
0
    public string getMessage()
    {
        NamedPipeClientStream pipe_client =
            new NamedPipeClientStream(".", pipe_name, PipeDirection.InOut);

        try
        {
            Console.WriteLine("connect");
            pipe_client.Connect();
            Console.WriteLine("connect--e");
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine("InvalidOperationException" + e);
        }
        StreamReader sr = new StreamReader(pipe_client);

        string message;
        while ((message = sr.ReadLine()) != null)
        {
            Console.WriteLine(message);
        }

        return "hoge";
    }
示例#20
0
 public override void evaluate()
 {
     try
     {
         if ((bool)pinInfo["trigger"].value.data && lastInput != pinInfo["trigger"].value.data)
         {
             myPipe = new NamedPipeClientStream(".", "lavalamp winamp control", PipeDirection.InOut,
                                                PipeOptions.None);
             myPipe.Connect(500);
             StreamWriter myWriter = new StreamWriter(myPipe);
             myWriter.AutoFlush = true;
             myWriter.Write(Cmd);
             myPipe.Close();
         }
         lastInput = pinInfo["trigger"].value;
     }
     catch (ObjectDisposedException)
     {
         // todo - add option to ignore errors / errored state / etc
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
     catch (IOException)
     {
         // todo - add option to ignore errors / errored state / etc
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
     catch (System.TimeoutException)
     {
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
 }
示例#21
0
 public static bool SendCommandToCore(string machine, string command)
 {
     NamedPipeClientStream pipeClient =
         new NamedPipeClientStream(machine, Kernel.MBCLIENT_MUTEX_ID,
         PipeDirection.Out, PipeOptions.None);
     StreamWriter sw = new StreamWriter(pipeClient);
     try
     {
         pipeClient.Connect(2000);
     }
     catch (TimeoutException)
     {
         Logger.ReportWarning("Unable to send command to core (may not be running).");
         return false;
     }
     try
     {
         sw.AutoFlush = true;
         sw.WriteLine(command);
         pipeClient.Flush();
         pipeClient.Close();
     }
     catch (Exception e)
     {
         Logger.ReportException("Error sending commmand to core", e);
         return false;
     }
     return true;
 }
示例#22
0
        private static void SendCommand(string sContent)
        {

            string sProgramName = ConfigurationManager.AppSettings["dstProgramName"];
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", sProgramName,
                                                                           PipeDirection.Out,
                                                                        PipeOptions.None))
            {
                
                Console.WriteLine("Attempting to connect to pipe...");
                try
                {
                    pipeClient.Connect(1000);
                }
                catch
                {
                    Console.WriteLine("The Pipe server must be started in order to send data to it.");
                    return;
                }
                Console.WriteLine("Connected to pipe.");

                using (StreamWriter sw = new StreamWriter(pipeClient))
                {
                    sw.Write(sContent);
                }
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".",
                                                                                "testpipe",
                                                                                PipeDirection.InOut))
            {

                // Connect to the pipe or wait until the pipe is available.
                Console.Write("Attempting to connect to pipe...");
                pipeClient.Connect();

                Console.WriteLine("Connected to pipe.");
                Console.WriteLine("There are currently {0} pipe server instances open.",
                   pipeClient.NumberOfServerInstances);

                while (pipeClient.IsConnected)
                {
                    using (StreamReader sr = new StreamReader(pipeClient))
                    {
                        // Display the read text to the console
                        string temp;
                        while ((temp = sr.ReadLine()) != null)
                        {
                            Console.WriteLine("Received from server: {0}", temp);
                        }
                    }
                }
            }
            Console.Write("Press Enter to continue...");
            Console.ReadLine();
        }
示例#24
0
		static void Main()
		{
			ClearModifierKeys();

			var args = Environment.GetCommandLineArgs();
			var multi = args.Any(arg => arg == "-multi");

			if ((multi) || (mutex.WaitOne(TimeSpan.Zero, true)))
			{
				var app = new App();
				if (!multi)
					SetupPipeWait(app);
				app.Run();
				if (!multi)
					mutex.ReleaseMutex();
				return;
			}

			// Server already exists; connect and send command line
			var pipeClient = new NamedPipeClientStream(".", IPCName, PipeDirection.InOut);
			pipeClient.Connect();
			var buf = Coder.StringToBytes(string.Join(" ", args.Skip(1).Select(arg => $"\"{arg.Replace(@"""", @"""""")}\"")), Coder.CodePage.UTF8);
			var size = BitConverter.GetBytes(buf.Length);
			pipeClient.Write(size, 0, size.Length);
			pipeClient.Write(buf, 0, buf.Length);
		}
示例#25
0
        public void CheckUnenrolledHostShouldRemoved()
        {
            CredentialReceiver.instance.Init();
            ServerListHelper.instance.Init();
            DatabaseManager.CreateNewConnection(dbName);
            IXenConnection connection = DatabaseManager.ConnectionFor(dbName);
            Session _session = DatabaseManager.ConnectionFor(dbName).Session;
            DatabaseManager.ConnectionFor(dbName).LoadCache(_session);
            Dictionary<string, string> config = cleanStack();
            connection.LoadCache(_session);

            int conSize = ServerListHelper.instance.GetServerList().Count;

            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { connection.Hostname, connection.Username, connection.Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            List<ServerInfo> con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 1);


            //1. If XenServer has not enroll, lock will not been set.
            config = cleanStack();
            config[HealthCheckSettings.STATUS] = "false";
            Pool.set_health_check_config(_session, connection.Cache.Pools[0].opaque_ref, config);
            Assert.IsFalse(RequestUploadTask.Request(connection, _session));
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            CredentialReceiver.instance.UnInit();
        }
示例#26
0
        public static Task<bool> SendMessageToServer(string pipeName, string message)
        {
            return Task.Run(() =>
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
                    {
                        pipe.Connect(1000);

                        using (var stream = new StreamWriter(pipe))
                        {
                            stream.Write(message);
                            stream.Flush();
                        }
                    }

                    return true;
                }
                catch (TimeoutException)
                {
                }
                catch (Exception exc)
                {
                    Log.Debug(string.Format("Sending message on: {0}", pipeName), exc);
                }

                return false;
            });
        }
示例#27
0
 static void Main(string[] args)
 {
     if (args.Length < 3)
         return;
     var pipe = new NamedPipeClientStream(args[2].Substring(9, args[2].Length - 9));
     pipe.Connect();
     var reader = new StreamReader(pipe);
     while(true)
     {
         if(reader.ReadLine().StartsWith("c:getPlatforms", StringComparison.InvariantCulture))
         {
             WriteNumber(pipe, -3085);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 2);
             WriteNumber(pipe, 8);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 2);
             WriteNumber(pipe, 10);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 0);
         }
     }
 }
示例#28
0
        static void Main()
        {
            using (Mutex mutex = new Mutex(false, @"Global\simpledlnaguilock")) {
            #if !DEBUG
            if (!mutex.WaitOne(0, false)) {
              using (var pipe = new NamedPipeClientStream(".", "simpledlnagui", PipeDirection.Out)) {
            try {
              pipe.Connect(10000);
              pipe.WriteByte(1);
            }
            catch (Exception) {
            }
            return;
              }
            }
            GC.Collect();
            #endif

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var main = new FormMain()) {
              try {
            Application.Run(main);
              }
              catch (Exception ex) {
            log4net.LogManager.GetLogger(typeof(Program)).Fatal("Encountered fatal unhandled exception", ex);
            throw;
              }
            }
              }
        }
        public void StartListening(Action<string> messageRecieved)
        {
            Task.Factory.StartNew(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                using (
                                    var pipe = new NamedPipeClientStream(".", "htmlbackground", PipeDirection.In,
                                                                         PipeOptions.Asynchronous))
                                {
                                    pipe.Connect(500);
                                    if (pipe.IsConnected)
                                    {
                                        using (var streamReader = new StreamReader(pipe))
                                        {
                                            var message = streamReader.ReadToEnd();

                                            if (messageRecieved != null)
                                            {
                                                // invoke the message received action
                                                messageRecieved(message);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (TimeoutException)
                            {
                            }
                        }
                    }, TaskCreationOptions.LongRunning);
        }
示例#30
0
        static void Main()
        {
            try
            {
                using (var pipe = new NamedPipeClientStream(".", "sharp-express", PipeDirection.InOut))
                {
                    pipe.Connect();

                    var encoding = Encoding.UTF8;
                    var sb = new StringBuilder();
                    sb.Append("GET / HTTP/1.1\r\n");
                    sb.Append("Header1: Hi!\r\n");
                    sb.Append("\r\n");

                    var bytes = encoding.GetBytes(sb.ToString());
                    pipe.Write(bytes, 0, bytes.Length);
                    pipe.Flush();

                    var buf = new byte[64 * 1024];
                    var size = pipe.Read(buf, 0, buf.Length);
                    var message = encoding.GetString(buf, 0, size);
                    Console.WriteLine(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }