/// <summary> /// 启动命名管道服务 /// </summary> /// <param name="a">客户端连接到 System.IO.Pipes.NamedPipeServerStream 对象时调用的方法。</param> /// <param name="pipeName"></param> public void Start(Action <StreamReader> action, string pipeName = "ALGZ_PIPE") { //Close(); if (pipeServer == null) { Load(pipeName); //重新加载命名管道 IAsyncResult result = pipeServer.BeginWaitForConnection((o) => { try { //NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState; pipeServer?.EndWaitForConnection(o); //阻塞,等待连接. if (pipeServer != null) { StreamReader sr = new StreamReader(pipeServer); action(sr); Close(); Start(action); } } catch (Exception ex) { ErrMsg = ex.Message; } }, pipeServer); } }
private void BeginWaitForConnection(IAsyncResult ar) { pipe.EndWaitForConnection(ar); if (pipe.IsConnected) { // Call OnConnected asynchronously if (OnConnected != null) { OnConnected.BeginInvoke(null, null); } pipe.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(BeginRead), null); } }
private int waitForAdditionalInstances(string[] args) { var accumulatedArgs = new List <string>(args); while (true) { var signal = new ManualResetEvent(false); using (var pipeServer = new NamedPipeServerStream(ipcNamedPipeGuid, PipeDirection.In, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { pipeServer.BeginWaitForConnection(x => { // if timed out, stop waiting for a connection if (signal.WaitOne(0)) { signal.Close(); return; } pipeServer.EndWaitForConnection(x); signal.Set(); }, null); // no client connected to the pipe within the Timeout period if (!signal.WaitOne(Timeout, true)) { signal.Set(); break; } using (var sr = new StreamReader(pipeServer)) { int length = Convert.ToInt32(sr.ReadLine()); for (int i = 0; i < length; ++i) { accumulatedArgs.Add(sr.ReadLine()); } } } // new args have been added to accumulatedArgs, continue loop to listen for another client } ipcMutex.Close(); var eventArgs = new SingleInstanceEventArgs(accumulatedArgs.ToArray()); Launching?.Invoke(this, eventArgs); return(eventArgs.ExitCode); }
void WaitForDataCallBack(IAsyncResult Result) { string Channel = null; NamedPipeServerStream pipeServer = null; dynamic Unpacker = null; try { object[] ObjState = (object[])Result.AsyncState; // Get the pipe pipeServer = (NamedPipeServerStream)(ObjState[0]); Channel = (string)ObjState[1]; //dynamic Converter = ObjState[2]; //var Receiver = SerializationContext.Default.GetSerializer<NPData<object>>(); Unpacker = ObjState[2]; // End waiting for the connection pipeServer.EndWaitForConnection(Result); //NPData<o> var NPData = Unpacker.Unpack(pipeServer); if (NPData != null && NPData.VerifyMessage == VerifyMessage && NPData.Channel == Channel && DataSyncAction.ContainsKey(Channel)) { DataSyncAction[Channel](NPData.Data); } //Clear Server if (pipeServer != null) { pipeServer.Dispose(); pipeServer = null; } } catch { //Cannot access close pipe //Happen when stop } if (Channel != null && Unpacker != null && DataSyncAction.ContainsKey(Channel)) { pipeServer = new NamedPipeServerStream(string.Format("{0}.{1}.{2}", PipeName, UniqueId, Channel), PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForDataCallBack), new object[3] { pipeServer, Channel, Unpacker }); } }
private void HandleConnection(IAsyncResult result) { eventLog.WriteEntry("Got incoming connection"); // Save the network config before we do anything. If the request fails // it will be sent to the client for inclusion in Sentry reports. var beforeNetworkInfo = GetNetworkInfo(); try { pipe.EndWaitForConnection(result); // Keep the pipe connected to send connection status updates. while (pipe.IsConnected) { ServiceResponse response = new ServiceResponse(); var request = ReadRequest(); if (request == null) { response.statusCode = (int)ErrorCode.GenericFailure; } else { response.action = request.action; try { HandleRequest(request); } catch (Exception e) { response.statusCode = (int)ErrorCode.GenericFailure; response.errorMessage = $"{e.Message} (network config: {beforeNetworkInfo})"; eventLog.WriteEntry($"request failed: {e.Message}", EventLogEntryType.Error); } } WriteResponse(response); } } catch (Exception e) { eventLog.WriteEntry($"Failed to handle connection: {e.ToString()}", EventLogEntryType.Error); } finally { // Pipe streams are one-to-one connections. Recreate the pipe to handle subsequent requests. DestroyPipe(); CreatePipe(); } }
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[255]; // Read message size pipeServer.Read(buffer, 0, 4); // Read message body int count = BitConverter.ToInt32(buffer, 0); // Clear buffer pipeServer.Read(buffer, 0, count); // Convert byte buffer to string string stringData = Encoding.UTF8.GetString(buffer, 0, count); try { // Pass message back to calling form PipeMessage.Invoke(stringData); } catch (Exception e) { Console.WriteLine(e.Message); } // 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; } }
private void Form1_Load(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(delegate { pipeServer.BeginWaitForConnection((o) => { NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState; pServer.EndWaitForConnection(o); StreamReader sr = new StreamReader(pServer); while (true) { this.Invoke((MethodInvoker) delegate { lsvMessage.Items.Add(sr.ReadLine()); }); } }, pipeServer); }); }
private void OnClientConnected(IAsyncResult result) { NamedPipeServerStream pipe = (NamedPipeServerStream)result.AsyncState; pipe.EndWaitForConnection(result); PipeHeaderData hd = m_pipes[pipe]; hd.state = null; hd.pipe = pipe; hd.data = new byte[BUFFER_SIZE]; m_handler.OnConnect(pipe, out hd.state); BeginRead(hd); }
private void ConnectionCallback(IAsyncResult ar) { try { _pipeServer.EndWaitForConnection(ar); _pipeServer.BeginRead(_bytes, 0, _bytes.Length, Callback, null); } catch (ObjectDisposedException) { // ignore } catch (Exception exception) { _logger.Log(exception); } }
static void FetchFile(IAsyncResult ar) { PipeListener(); NamedPipeServerStream server = ar.AsyncState as NamedPipeServerStream; server.EndWaitForConnection(ar); using (StreamReader reader = new StreamReader(server)) { lock (SubmittedFiles) { while (!reader.EndOfStream) { SubmittedFiles.Add(reader.ReadLine()); } } } server.Dispose(); }
private void OnConnection(IAsyncResult ar) { try { svPipe.EndWaitForConnection(ar); } catch (ObjectDisposedException) { return; } if (!svPipe.IsConnected) { return; } var thread = new Thread(ClientServiceLoop); thread.Name = "PipeConsoleServer"; thread.IsBackground = true; thread.Start(); }
/// <summary> /// Called when a client connect to the pipe /// </summary> /// <param name="result">The result of the asynchronous operation</param> private void OnPipeConnect(IAsyncResult result) { logger_.Log(Level.Info, "Pipe connected"); // Accept the connection pipe_.EndWaitForConnection(result); if (W) { logger_.Log(Level.Info, "Writing wireshark global header to pipe(presume client is Wireshark)"); //modified for wireshark trace function, temporary hardcoded //writing a struct pcap_hdr_s when wireshark client is connected //https://wiki.wireshark.org/Development/LibpcapFileFormat byte[] buffer = new byte[] { 0xd4, 0xc3, 0xb2, 0xa1, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00 }; pipe_.Write(buffer, 0, 24); } // }
private static void PipeConnectionCallBack(IAsyncResult ar) { Hoofdscherm main_form = (Hoofdscherm)((object[])ar.AsyncState)[1]; pipeServer = new NamedPipeServerStream("Drawit_pipeserver", PipeDirection.InOut, 15, PipeTransmissionMode.Message, PipeOptions.Asynchronous); result = pipeServer.BeginWaitForConnection(new AsyncCallback(PipeConnectionCallBack), new object[] { pipeServer, main_form }); NamedPipeServerStream pipe_server = (NamedPipeServerStream)((object[])ar.AsyncState)[0]; pipe_server.EndWaitForConnection(ar); StreamString ss = new StreamString(pipe_server); string filename = ss.ReadString(); main_form.Invoke((Action) delegate { main_form.OpenFile(filename); }); pipe_server.Close(); pipe_server.Dispose(); }
private void WaitForConnectionCallBack(IAsyncResult result) { try { _server.EndWaitForConnection(result); var message = _formatter.Deserialize(_server); Debug.WriteLine($"[ <= ] New message of type {message.GetType().Name} received on pipe {_pipeName.Read}"); _ignoreMe.Add(message.MsgId); OnMessageReceived(message); _server.Disconnect(); _server.BeginWaitForConnection(WaitForConnectionCallBack, null); } catch { return; } }
/// <summary> /// The function called when a client connects to the named pipe. Note: This method is called on a non-UI thread. /// </summary> /// <param name="iAsyncResult"></param> private void NamedPipeServerConnectionCallback(IAsyncResult iAsyncResult) { try { // End waiting for the connection _namedPipeServerStream.EndWaitForConnection(iAsyncResult); // Read data and prevent access to _namedPipeXmlPayload during threaded operations lock (_namedPiperServerThreadLock) { // Read data from client var xmlSerializer = new XmlSerializer(typeof(NamedPipeXmlPayload)); _namedPipeXmlPayload = (NamedPipeXmlPayload)xmlSerializer.Deserialize(_namedPipeServerStream); // _namedPipeXmlPayload contains the data sent from the other instance // As an example output it to the textbox // In more complicated cases would need to do some processing here and possibly pass to UI thread ////////////////// ////////////////// ////////////////// ////////////////// /// } } catch (ObjectDisposedException) { // EndWaitForConnection will exception when someone closes the pipe before connection made // In that case we dont create any more pipes and just return // This will happen when app is closing and our pipe is closed/disposed return; } catch (Exception) { // ignored } finally { // Close the original pipe (we will create a new one each time) _namedPipeServerStream.Dispose(); } // Create a new pipe for next connection NamedPipeServerCreateServer(); FormsExternalStuff.RecievedMessageCheck(_namedPipeXmlPayload.Payload[0].ToString()); }
/// <summary> /// The function called when a client connects to the named pipe. Note: This method is called on a non-UI thread. /// </summary> /// <param name="iAsyncResult"></param> public static void NamedPipeServerConnectionCallback(IAsyncResult iAsyncResult) { try { // End waiting for the connection _namedPipeServerStream.EndWaitForConnection(iAsyncResult); // Read data and prevent access to _namedPipeXmlPayload during threaded operations lock (_namedPiperServerThreadLock) { // Read data from client //var xmlSerializer = new XmlSerializer(typeof(NamedPipeXmlPayload)); IFormatter f = new BinaryFormatter(); _namedPipePayload = (NamedPipePayload)(f.Deserialize(_namedPipeServerStream)); if (_namedPipePayload.SignalQuit) { return; } //Console.WriteLine("Got Authenticaiton Response."); // _namedPipeXmlPayload contains the data sent from the other instance //Console.WriteLine(_namedPipePayload.Arguments); Authentication.ProcessAuthenticationResponse(_namedPipePayload.Arguments); } } catch (ObjectDisposedException) { // EndWaitForConnection will exception when someone closes the pipe before connection made // In that case we dont create any more pipes and just return // This will happen when app is closing and our pipe is closed/disposed return; } catch (Exception) { // ignored } finally { // Close the original pipe (we will create a new one each time) _namedPipeServerStream.Dispose(); } // Create a new pipe for next connection NamedPipeServerCreateServer(); }
// Named Pipes client connection private void OnClientConnected(IAsyncResult result) { // complete the client connection NamedPipeServerStream pipe = (NamedPipeServerStream)result.AsyncState; pipe.EndWaitForConnection(result); // create client pipe structure IpcPipeData pd = new IpcPipeData(); pd.pipe = pipe; pd.state = null; pd.data = new Byte[SERVER_IN_BUFFER_SIZE]; // add connection to connection list bool running; lock (pipeDict) { running = isRunning; if (running) { pipeDict.Add(pd.pipe, pd); } } // if server is still running if (running) { // prepare for next connection CreatePipe(); // alert server that client connection exists -> increment count Int32 count = System.Threading.Interlocked.Increment(ref instanceCounter); WriteVerboseToLog("Client connected to server instance " + count + "."); pd.state = count; // accept messages WriteVerboseToLog("Server instance " + count + ": start reading message."); BeginRead(pd); } else { pipe.Close(); } }
private void WaitForConnectionCallBack(IAsyncResult iar) { try { // Get the pipe NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState; // End waiting for the connection pipeServer.EndWaitForConnection(iar); Debug.WriteLine("Client connected to named pipe"); _isConnected = true; OnClientConnected(EventArgs.Empty); } catch { // } }
private void PipeConnect(IAsyncResult iar) { if (!_IsRunning) { return; } _MainPipe.EndWaitForConnection(iar); _MainPipe.Write(_PipeData, 0, _PipeData.Length); _MainPipe.WaitForPipeDrain(); _MainPipe.Disconnect(); // neue Pipe erstellen, einmal geschlossen, wars das _MainPipe.BeginWaitForConnection(PipeConnect, null); }
private void WaitForConnectionCallBack(IAsyncResult iar) { NamedPipeServerStream pipe = (NamedPipeServerStream)iar.AsyncState; try { // Get the pipe // End waiting for the connection pipe.EndWaitForConnection(iar); byte[] buffer = new byte[0]; // Read the incoming message while (true) { byte[] buf = new byte[256]; var counter = pipe.Read(buf, 0, 256); if (counter == 0) { break; } buffer = buffer.AppendArray(buf); } // Convert byte buffer to string string stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length); Debug.WriteLine(stringData); // Pass message back to calling form T message = JsonConvert.DeserializeObject <T>(stringData); PipeMessage.Invoke(this, message); } catch (Exception ex) { ex.Message.ErrorLognConsole(); return; } finally { // Kill original sever and create new wait server pipe.Close(); pipe = null; pipe = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); // Recursively wait for the connection again and again.... pipe.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipe); } }
void IpcProcessConnection(IAsyncResult ar) { try { // connect and read command ipcServer.EndWaitForConnection(ar); int raw = ipcServer.ReadByte(); if (raw >= 0) { IpcCommands command = (IpcCommands)raw; // commands interact with the main form and must therefore be processed in the UI thread this.Dispatcher.Invoke(new Action(() => { try { if (command == IpcCommands.ShowMainWindow) { this.MainWindow.ShowWindow(); } else if (command == IpcCommands.Exit) { this.MainWindow.CloseWindow(); } } catch (Exception ex) { log.Error("Error processing Ipc Message: " + ex.Message + " (" + ex.GetType().Name + ")", ex); } })); } } catch (Exception ex) { log.Error("Error processing Ipc Message: " + ex.Message + " (" + ex.GetType().Name + ")", ex); } try { ipcServer.Disconnect(); ipcServer.BeginWaitForConnection(new AsyncCallback(IpcProcessConnection), null); } catch (Exception ex) { log.Error("Could not listen on Ipc Channel: " + ex.Message + " (" + ex.GetType().Name + ")", ex); } }
private void WaitForConnectionCallBack(IAsyncResult result) { if (!m_isStopping) { lock (m_lockingObject) { if (!m_isStopping) { m_pipe.EndWaitForConnection(result); OnConnected(); BeginRead(new Info()); } } } }
private void OnClientConnected(IAsyncResult result) { try { // Complete the client connection NamedPipeServerStream pipe = (NamedPipeServerStream)result.AsyncState; pipe.EndWaitForConnection(result); // Create client pipe structure IpcPipeData pd = new IpcPipeData(); pd.pipe = pipe; pd.state = null; pd.data = new Byte[SERVER_IN_BUFFER_SIZE]; // Add connection to connection list bool running; lock (m_pipes) { running = m_running; if (running) { m_pipes.Add(pd.pipe, pd); } } // If server is still running if (running) { // Prepare for next connection IpcServerPipeCreate(); // Alert server that client connection exists m_callback.OnAsyncConnect(pipe, out pd.state); // Accept messages BeginRead(pd); } else { pipe.Close(); } } catch (Exception ex) { //Exception reason: NamedPipeServerStream.close() is called when stopped the server. This causes OnClientConnected to be called. It then tries to acces a closed pipe with pipe.EndWaitForConnection } }
private void Config(IAsyncResult ar) { try { configPipe.EndWaitForConnection(ar); var command = new StreamReader(configPipe).ReadLine(); var writer = new StreamWriter(configPipe) { AutoFlush = true }; if (command == "reload") { try { Config(); writer.WriteLine("load " + options.Length + " log rotater" + (options.Length > 1 ? "s" : "") + "."); WriteOptions(writer); } catch (Exception e) { writer.Write("reload failed : " + e.Message); } } else if (command == "status") { writer.WriteLine(options.Length + " log rotater" + (options.Length > 1 ? "s are " : " is ") + (rotateSecond == -1 ? "stopped" : "running") + "."); WriteOptions(writer); } else { writer.WriteLine("invalid command: " + command); } configPipe.WaitForPipeDrain(); } catch (Exception e) { Trace.TraceError("config fault: " + e); } finally { configPipe.Disconnect(); configPipe.BeginWaitForConnection(Config, ar.AsyncState); } }
private void WaitForConnectionCallBack(IAsyncResult Ar) { try { Pipe.EndWaitForConnection(Ar); if (IsPipeConnected) { SetOnPipeConnected(); StartReceivingData(); } } catch (Exception ex) { SetOnPipeException(ex); ClosePipeServer(); } }
private void asyncConnected(IAsyncResult ar) { pipe.EndWaitForConnection(ar); if (ar.IsCompleted) { bytesReceived = 0; bytesExpected = 4; // length of incoming string receiveMode = 0; // string length try { if (buffer.Length < bytesExpected) { buffer = new byte[bytesExpected]; } //pipe.ReadAsync(buffer, bytesReceived, bytesExpected - bytesReceived).ContinueWith(received); pipe.BeginRead(buffer, bytesReceived, bytesExpected - bytesReceived, asyncReceived, null); } catch { } } }
private void ClientConnected(IAsyncResult result) { NamedPipeServerStream asyncState = result.AsyncState as NamedPipeServerStream; asyncState.EndWaitForConnection(result); if (asyncState.IsConnected) { NamedPipeTransport item = new NamedPipeTransport(asyncState, PipeName); item.MessageReceived += new MessageEventHandler(OnMessageReceived); lock (mConnections) { mConnections.Add(item); } } NamedPipeServerStream state = new NamedPipeServerStream(PipeName, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); state.BeginWaitForConnection(new AsyncCallback(this.ClientConnected), state); }
/// <summary> /// This callback is called when the async WaitForConnection operation is completed, /// whether a connection was made or not. WaitForConnection can be completed when the server disconnects. /// </summary> private void WaitForConnectionCallBack(IAsyncResult result) { if (!_isStopping) { lock (_lockingObject) { if (!_isStopping) { // Call EndWaitForConnection to complete the connection operation _pipeServer.EndWaitForConnection(result); OnConnected(); BeginRead(new Info()); } } } }
private static void _AsyncConnectionHandler(IAsyncResult result) { NamedPipeServerStream srv = result.AsyncState as NamedPipeServerStream; srv.EndWaitForConnection(result); BinaryFormatter bf = new BinaryFormatter(); string[] inargs = bf.Deserialize(srv) as string[]; AddFiles(inargs); srv.Close(); srv = new NamedPipeServerStream(_AppName + "IPC", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); srv.BeginWaitForConnection(new AsyncCallback(_AsyncConnectionHandler), srv); }
static void PipeHandler(IAsyncResult res) { NamedPipeServerStream nps = res.AsyncState as NamedPipeServerStream; // End the current connection. nps.EndWaitForConnection(res); string data = Name + ":" + Port + "\r\n"; nps.Write(Encoding.ASCII.GetBytes(data), 0, data.Length); nps.Flush(); nps.WaitForPipeDrain(); nps.Disconnect(); // Start the new connection. nps.BeginWaitForConnection(PipeHandler, nps); }