private void OnConnectionAsync(IAsyncResult ar) { if (_pipeServer == null) { ReleaseServerReference(false); return; } try { _pipeServer.EndWaitForConnection(ar); } catch (Exception ex) { ReleaseServerReference(false); MessageBox.Show(ex.Message, "RpcServer", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Debug.WriteLine($"New pipe connection"); AddDispatchEvent(new ConnectedRpcEvent()); _pipeServer.BeginRead(_readBuffer, 0, _readBuffer.Length, OnReadAsync, null); }
private static void BeginReceiveHeader() { try { if (_client != null && _client.IsConnected) { headerBuffer = new byte[sizeof(int)]; _client.BeginRead(headerBuffer, 0, sizeof(int), delegate(IAsyncResult ar) { try { _client.EndRead(ar); var msgSize = BitConverter.ToInt32((byte[])ar.AsyncState, 0); BeginReceiveMessage(msgSize); } catch { CloseClient(); } }, headerBuffer); } } catch { CloseClient(); } }
private void ClientConnected(IAsyncResult result) { new PipeServer(); m_Pipe.EndWaitForConnection(result); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); Byte[] data = new Byte[1000]; m_Pipe.BeginRead(data, 0, data.Length, GetRequest, data); }
private void ConnectionCompleted(IAsyncResult result) { if (isDisposed) { return; } serverStream.EndWaitForConnection(result); Connected?.Invoke(this, new NamedPipeServerConnectedEventArgs { ConnectionId = id }); serverStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null); }
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); } }
/// <summary> /// Handle a new connection on the server stream. End the waitfor connection and restart waiting on a new serverstream. /// </summary> /// <param name="iAsyncResult"></param> private void _pipeConnected(IAsyncResult iAsyncResult) { //Get the connecting client from the asyncstate and end the connection process AsyncPipeStateWrapper wrapper = iAsyncResult.AsyncState as AsyncPipeStateWrapper; NamedPipeServerStream connectingClient = wrapper.NamedPipeServerStream; connectingClient.EndWaitForConnection(iAsyncResult); //Double-check the damn connection is actually connected if (connectingClient.IsConnected) { //Lock the connecting client and start a read on it byte[] readBuffer = new byte[SIZE_BUFFER]; lock (connectingClient) { connectingClient.BeginRead(readBuffer, 0, SIZE_BUFFER, new AsyncCallback(_endRead), new AsyncPipeStateWrapper(connectingClient, readBuffer)); } //The namedPipeServerStream BECOMES the connection object after it connects. //Lock the list to avoid thread issues lock (_connectedPipeStreams) { _connectedPipeStreams.Add(connectingClient); } } //Restart the pipe waiting for connection NamedPipeServerStream newConnection = new NamedPipeServerStream(SB_PIPE_NAME, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); newConnection.BeginWaitForConnection(new AsyncCallback(this._pipeConnected), new AsyncPipeStateWrapper(newConnection, null)); }
void ReadFromQueue() { if (!_serverStream.IsConnected) { return; } _serverStream.BeginRead(_readBuffer, 0, MaxMessage, ar => { try { var bytes = _serverStream.EndRead(ar); if (bytes == 0) { Trace("Connection closed."); _isConnected = false; return; } var message = _formatter.Deserialize(new MemoryStream(_readBuffer)); _inProcQueue.Enqueue(message); ReadFromQueue(); } catch (Exception ex) { _isConnected = false; Trace("Connection closed with error: {0}.", ex.Message); } }, null); }
bool Oku(NamedPipeServerStream Akış, int ZamanAşımı_msn, out byte[] Çıktı, int Adet) { Çıktı = new byte[Adet]; try { int Tik = Environment.TickCount + ZamanAşımı_msn; IAsyncResult Döngü = Akış.BeginRead(Çıktı, 0, Adet, null, null); while (Environment.TickCount < Tik && !Döngü.IsCompleted) { Thread.Sleep(2); } if (Döngü.IsCompleted) { Tik = Akış.EndRead(Döngü); if (Tik == Adet) { return(true); } } } catch (Exception) { } return(false); }
/// <summary> /// Handle on client connected /// </summary> /// <param name="result">AsyncResult</param> private void OnClientConnected(IAsyncResult result) { IpcPipe pipeInst = (IpcPipe)result.AsyncState; // Complete the client connection NamedPipeServerStream pipe = (NamedPipeServerStream)result.AsyncState; try { pipe.EndWaitForConnection(result); } catch (Exception ex) { Console.WriteLine(ex.Message + " >" + ex.StackTrace); pipeInst.m_options.m_callBackObj.OnNewConnection(this, IpcConnectStatus.FAIL_WAIT_FOR_CONNECTION_FAILED); return; } try { m_pipeHandle.BeginRead(m_readBuffer, 0, m_options.m_numOfReadBytes, OnReadComplete, this); m_connected = true; m_options.m_callBackObj.OnNewConnection(this, IpcConnectStatus.SUCCESS); } catch (System.Exception ex) { Console.WriteLine(ex.Message + " >" + ex.StackTrace); KillConnection(); m_options.m_callBackObj.OnNewConnection(this, IpcConnectStatus.FAIL_READ_FAILED); } }
/// <summary> /// Handles the connected event of the <see cref="NamedPipeServerStream"/> object. /// </summary> /// <param name="ar">The <see cref="IAsyncResult"/>s that contains connection information.</param> private void NamedPipeConnected(IAsyncResult ar) { if (mPipedStream != null && ar.IsCompleted) { try { mPipedStream.EndWaitForConnection(ar); byte[] cmdLineBuffer = new byte[8191]; mPipedStream.BeginRead( cmdLineBuffer , 0 , cmdLineBuffer.Length , NamedPipeRead , cmdLineBuffer); } catch (ObjectDisposedException) { // On closing the application the named piped may throw a disposed exception. // We ignore this on closing. } catch (Exception ex) { Logger.Error(ex.Message); } } }
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); } }
private void onClientDataReceived(IAsyncResult asyncResult) { pipeServer.EndRead(asyncResult); if (inBuffer.Length == 0) { return; } EProtocol protocol = (EProtocol)inBuffer[0]; switch (protocol) { case EProtocol.SetAttach: EAttachPoint attachPoint = (EAttachPoint)inBuffer[1]; int x = inBuffer[2]; int y = inBuffer[3]; LogManager.Instance.Log(String.Format("Client Command: 修改挂点: {0}-{1},{2}", attachPoint.ToString(), x, y)); break; } try { if (pipeServer.IsConnected) { pipeServer.Flush(); pipeServer.BeginRead(inBuffer, 0, pipeServer.InBufferSize, onClientDataReceived, pipeServer); } } catch (Exception e) { throw e; } }
public override int Read(byte[] buf, int off, int len) { if (stream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } #if !NET_CORE if (asyncMode) { Exception eOuter = null; var evt = new ManualResetEvent(false); int retval = 0; stream.BeginRead(buf, off, len, asyncResult => { try { if (stream != null) { retval = stream.EndRead(asyncResult); } else { eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted); } } catch (Exception e) { if (stream != null) { eOuter = e; } else { eOuter = new TTransportException(TTransportException.ExceptionType.Interrupted, e.Message); } } evt.Set(); }, null); evt.WaitOne(); if (eOuter != null) { throw eOuter; // rethrow exception } else { return(retval); } } else { return(stream.Read(buf, off, len)); } #else return(stream.Read(buf, off, len)); #endif }
private void ClientConnected(IAsyncResult result) { new PipeServer(); m_pipe.EndWaitForConnection(result); Byte[] data = new byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotRequest, data); }
/// <summary> /// Extends BeginRead so that when a state object is not needed, null does not need to be passed. /// <example> /// pipestream.BeginRead(buffer, offset, count, callback); /// </example> /// </summary> public static IAsyncResult BeginRead(this NamedPipeServerStream pipestream, Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback) { if (pipestream == null) { throw new ArgumentNullException("pipestream"); } return(pipestream.BeginRead(buffer, offset, count, callback, null)); }
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 WaitForRead(IAsyncResult pAr) { var read = _pipeServer.EndRead(_readAsync); if (read == 0) { _pipeServer.Disconnect(); _pipeServer.BeginWaitForConnection(WaitForConnection, null); _readAsync = null; } else { var buf = new byte[read]; Array.Copy(_buffer, 0, buf, 0, read); UtilityMethods.ReadMessage(buf, _messageReaders); _readAsync = _pipeServer.BeginRead(_buffer, 0, _buffer.Length, WaitForRead, null); } }
private void onRead(IAsyncResult ar) { NamedPipeServerStream cNamedPipeServer = ar.AsyncState as NamedPipeServerStream; try { int iNumBytes = cNamedPipeServer.EndRead(ar); if (iNumBytes == 0) { cNamedPipeServer.Close(); cNamedPipeServer.Dispose(); Listen(); } else { if (iNumBytes < MAX_BUFFER_SIZE) { byte[] bData = __cBuffer; if (__cMemStream.Position > 0) { __cMemStream.Write(__cBuffer, 0, iNumBytes); bData = __cMemStream.GetBuffer(); iNumBytes = (int)__cMemStream.Position; __cMemStream.Position = 0; } string sText = Encoding.UTF8.GetString(bData, 0, iNumBytes); if (onMessage != null) { onMessage(this, new MessageEvent() { Buffer = bData, Length = iNumBytes, Message = sText }); } } else { __cMemStream.Write(__cBuffer, 0, iNumBytes); } cNamedPipeServer.BeginRead(__cBuffer, 0, MAX_BUFFER_SIZE, onRead, cNamedPipeServer); } } catch (Exception __errExcep) { if (logger.IsErrorEnabled) { logger.ErrorFormat("{0}\r\n{1}", __errExcep.Message, __errExcep.StackTrace); } cNamedPipeServer.Close(); cNamedPipeServer.Dispose(); } }
private void ClientConnected(IAsyncResult result) { //一个客户端建立了连接,让我们接受另一个客户端 new PipleServer(); //接受客户端连接 m_pipe.EndWaitForConnection(result); byte[] data = new byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotRequest, data); }
void SerializeDeserializeAsync(NamedPipeServerStream pipe, ProcessThreadParams parameters, Action <ProcessThreadResult> callback) { var formatter = new BinaryFormatter(); pipe.BeginWaitForConnection((ar) => { pipe.EndWaitForConnection(ar); var memory = new MemoryStream(); formatter.Serialize(memory, parameters); var lengthBytes = BitConverter.GetBytes((int)memory.Length); pipe.Write(lengthBytes, 0, 4); memory.WriteTo(pipe); var buf = new byte[1024]; memory = new MemoryStream(); AsyncCallback endread = null; endread = reader => { int bytesRead = pipe.EndRead(reader); if (bytesRead == 0) { pipe.Close(); memory.Position = 0; if (memory.Length != 0) { var result = (ProcessThreadResult)formatter.Deserialize(memory); callback(result); } } else { memory.Write(buf, 0, bytesRead); pipe.BeginRead(buf, 0, buf.Length, endread, null); } }; pipe.BeginRead(buf, 0, buf.Length, endread, null); }, null); }
private static IEnumerator <Int32> PipeServerAsyncEnumerator(AsyncEnumerator ae) { // Each server object performs asynchronous operations 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()); // Get the timestamp of this client's request DateTime now = DateTime.Now; // We want to save the timestamp of the most-recent client request. Since multiple // clients are running concurrently, this has to be done in a thread-safe way s_gate.BeginRegion(SyncGateMode.Exclusive, ae.End()); // Request exclusive access yield return(1); // The iterator resumes when exclusive access is granted if (s_lastClientRequestTimestamp < now) { s_lastClientRequestTimestamp = now; } s_gate.EndRegion(ae.DequeueAsyncResult()); // Relinquish exclusive access // My sample server just changes all the characters to uppercase // But, you can replace this code with any compute-bound operation 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 the pipe }
private void ClientConnected(IAsyncResult result) { // A client connected, let's accept another client new PipeServer(); // Accept another client // Accept the client connection m_pipe.EndWaitForConnection(result); // Asynchronously read a request from the client Byte[] data = new Byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotRequest, data); }
private void BeginRead(Info info) { try { m_pipe.BeginRead(info.m_buffer, 0, BufferSize, EndReadCallBack, info); } catch (Exception ex) { service.Output.WriteError(ex.ToString()); throw; } }
/// <summary> /// This method begins an asynchronous read operation. /// </summary> private void BeginRead(Info info) { try { _pipeServer.BeginRead(info.Buffer, 0, BufferSize, EndReadCallBack, info); } catch (Exception ex) { Logger.Error(ex); throw; } }
private void OnReceive(IAsyncResult asyncResult) { try { int received = myNamedPipeServerStream.EndRead(asyncResult); if (received > 0) { lock (myMemoryStreamLock) { myMemoryStream.Write(myBuffer, 0, received); Monitor.Pulse(myMemoryStreamLock); } } if (myNamedPipeServerStream.IsConnected) { myNamedPipeServerStream.BeginRead(myBuffer, 0, myBuffer.Length, new AsyncCallback(OnReceive), null); } } catch (ObjectDisposedException) { } catch (InvalidOperationException) { } }
//=================================================================== // 多重起動防止 //=================================================================== /// NamedPipeServerStreamを生成する private void StartPipeServer(SynchronizationContext context) { Debug.WriteLine("[OPEN]", "NamedPipe"); var pipe = new NamedPipeServerStream(App.namedPipeName, PipeDirection.In, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); try { pipe.BeginWaitForConnection((result) => { try { pipe.EndWaitForConnection(result); // 新しいPipeを生成 this.StartPipeServer(context); // Read var data = new byte[1024]; // 260文字(MAX_PATH)x3byte、改行とオプション分 pipe.BeginRead(data, 0, data.Length, (readResult) => { var args = new CommandLineArgs(); try { var actualLength = pipe.EndRead(readResult); args = new CommandLineArgs(data, actualLength); } catch { // 出来なければできないでOK Debug.WriteLine("Read named pipe failed", "App.StartPipeServer"); return; } finally { pipe.Close(); } Debug.WriteLine("CLI feature requested:"); context.Post((state) => { if (args.ProfilePathOption) { App.Impl.OpenProfile(args.ProfilePath); } this.ParseAndRun(args, true); }, null); Debug.WriteLine("[CLOSE]", "NamedPipe"); }, null); } catch { // 出来なければできないでOK Debug.WriteLine("Connect named pipe failed", "App.StartPipeServer"); pipe.Close(); } }, null); } catch { // 出来なければできないでOK Debug.WriteLine("Start named pipe failed", "App.StartPipeServer"); pipe.Close(); } }
private void OnConnection(IAsyncResult result) { try { _pipe.EndWaitForConnection(result); if (!_pipe.IsConnected) { return; } var pipeState = new PipeState(); _pipe.BeginRead(pipeState.Buffer, 0, pipeState.Buffer.Length, OnReadFinished, pipeState); } catch (ObjectDisposedException) { if (!_disposable.IsDisposed) { throw; } } }
private void BeginRead() { try { _server.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, null); } catch (Exception) { if (OnDisconnected != null) { OnDisconnected(this); } } }
public void Read_from_Client_Async() { if (namedPipeServerStream != null) { if (namedPipeServerStream.CanRead && namedPipeServerStream.IsConnected) { namedPipeServerStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 1); } else { close_pipe(); } } }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// pipestream.BeginRead(buffer, callback); /// </example> /// </summary> public static IAsyncResult BeginRead(this NamedPipeServerStream pipestream, Byte[] buffer, AsyncCallback callback) { if (pipestream == null) { throw new ArgumentNullException("pipestream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } return(pipestream.BeginRead(buffer, 0, buffer.Length, callback)); }