private static void BeginReceiveHeader() { try { if (_clientStream != null && _clientStream.IsConnected) { headerBuffer = new byte[sizeof(int)]; _clientStream.BeginRead(headerBuffer, 0, sizeof(int), delegate(IAsyncResult ar) { try { _clientStream.EndRead(ar); int msgSize = BitConverter.ToInt32(((byte[])ar.AsyncState), 0); BeginReceiveMessage(msgSize); } catch { Disconnect(); } }, headerBuffer); } } catch { Disconnect(); } }
public IObservable <byte[]> Receive() { Connect(); var pipeState = new PipeState(); _pipe.BeginRead(pipeState.Buffer, 0, pipeState.Buffer.Length, OnReadFinished, pipeState); return(_messages); }
public void Connect(int timeout) { if (disposedValue) { throw new ObjectDisposedException("NamedIpcClient"); } clientRead.Connect(timeout); clientWrite.Connect(timeout); clientRead.BeginRead(clientBuff, 0, clientBuff.Length, ClientReadCallback, null); }
private void ReadCompleted(IAsyncResult result) { int readBytes = clientStream.EndRead(result); if (readBytes > 0) { messageBuilder.Append(Encoding.UTF8.GetString(buffer, 0, readBytes)); if (!clientStream.IsMessageComplete) { clientStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null); } else { string message = messageBuilder.ToString().TrimEnd('\0'); messageBuilder.Clear(); if (messageBuilder.Capacity > 64 * 1024) { messageBuilder.Capacity = buffer.Length; } synchronizationContext.Post( a => Message?.Invoke(this, (NamedPipeClientMessageEventArgs)a), new NamedPipeClientMessageEventArgs(this) { Message = message }); // Continue reading for next message clientStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null); } } else { if (!isDisposed) { synchronizationContext.Post(a => Disconnected?.Invoke(this, (EventArgs)a), EventArgs.Empty); if (Reconnect) { Connect(Timeout.Infinite); synchronizationContext.Post(a => Reconnected?.Invoke(this, (EventArgs)a), EventArgs.Empty); } else { Dispose(); } } } }
static void EndReadCallBack(IAsyncResult result) { try { var readBytes = RecvStream.EndRead(result); if (readBytes > 0) { string message = Encoding.UTF8.GetString(MsgBuf, 0, readBytes); MsgHandler(message); RecvStream.BeginRead(MsgBuf, 0, BufferSize, EndReadCallBack, null); } else // When no bytes were read, it can mean that the client have been disconnected { log.Info("Named pipe received empty content, close pipe"); RecvStream.Close(); RecvStream.Dispose(); } } catch (Exception ex) { log.Error("Named pipe error, close pipe. ex: " + ex); RecvStream.Close(); RecvStream.Dispose(); } }
protected void Reconnect() { if (_messageTypes == null) { var lst = MessageReaders.ToList(); lst.Add(new MessageReader <ShutDownInfo>(ShutDownMessage.MessageKey) { MessageRecieved = OnShutDown }); _messageTypes = lst.ToArray(); } _pipe = new NamedPipeClientStream("localhost", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); if (Connecting != null) { Connecting(); } _pipe.Connect(); if (Connected != null) { Connected(); } _pipe.BeginRead(_buffer, 0, _buffer.Length, OnReadData, null); }
/// <summary> /// End an asynchronous read operation, fire off the StateObjectReceived event if we read /// the whole object, and start a new asynchronous read operation. /// </summary> /// <param name="iAsyncResult"></param> private void _endRead(IAsyncResult iAsyncResult) { //Get the length of everything read in the stream, blocking 'til we're done reading int length = _pipeClientStream.EndRead(iAsyncResult); //Get the buffer from the async result byte[] previousBuffer = (byte[])iAsyncResult.AsyncState; //If we've read -something- if (length > 0) { //copy the start buffer into the new buffer byte[] endBuffer = new byte[length]; Array.Copy(previousBuffer, 0, endBuffer, 0, length); //Woohoo. We just received a state object. using (MemoryStream memStream = new MemoryStream(endBuffer)) { //Deserialize it and fire the event if possible UiStateObject stateObject = Serializer.Deserialize <UiStateObject>(memStream); if (UiStateObjectReceived != null) { UiStateObjectReceived(this, new UiStateObjectEventArgs(stateObject)); } } } //Get the connection lock and start another asynch read lock (_connectionLock) { //Sanitize the read buffer. previousBuffer = new byte[SIZE_BUFFER]; _pipeClientStream.BeginRead(previousBuffer, 0, SIZE_BUFFER, new AsyncCallback(this._endRead), previousBuffer); } }
private void BeginReadStream() { if (isClosed) { return; } try { lock (streamLock) { if (stream == null || !stream.IsConnected) { return; } stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(EndReadStream), stream.IsConnected); } } catch (ObjectDisposedException) { return; } catch (InvalidOperationException) { // The pipe has been closed return; } catch { // Unknown error } }
private static IEnumerator <Int32> PipeClientAsyncEnumerator(AsyncEnumerator ae, String serverName, String message) { // Each client object performs asynchronous operations on this pipe using (var pipe = new NamedPipeClientStream(serverName, "Echo", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { pipe.Connect(); // Must Connect before setting ReadMode pipe.ReadMode = PipeTransmissionMode.Message; // Asynchronously send data to the server Byte[] output = Encoding.UTF8.GetBytes(message); pipe.BeginWrite(output, 0, output.Length, ae.End(), null); yield return(1); // The data was sent to the server pipe.EndWrite(ae.DequeueAsyncResult()); // Asynchronously read the server's response Byte[] data = new Byte[1000]; pipe.BeginRead(data, 0, data.Length, ae.End(), data); yield return(1); // The server responded, display the response and close out connection Int32 bytesRead = pipe.EndRead(ae.DequeueAsyncResult()); Console.WriteLine("Server response: " + Encoding.UTF8.GetString(data, 0, bytesRead)); } // Close(); }
bool Oku(NamedPipeClientStream 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); }
private void BeginReadCommand() { if (CommandStream != null && CommandStream.IsConnected) { CommandStream.BeginRead(Command, 0, Constants.COMMAND_PIPELINE_BUFFER_SIZE, ReadCommandAsyncCallback, null); } }
private void _writeDone(IAsyncResult result) { //响应已发给了客户端,关闭我们的这段连接 m_pipe.EndWrite(result); byte[] data = new byte[1000]; m_pipe.BeginRead(data, 0, data.Length, _gotResponse, data); }
private void WriteDone(IAsyncResult ar) { m_pipe.EndWrite(ar); var data = new byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotResponse, data); }
public void Start(string pipeName, string id) { _pipe = new NamedPipeClientStream(pipeName); _pipe.Connect(); _pipe.BeginRead(_readBuffer, 0, _readBuffer.Length, OnRead, null); Write("hello", id); }
void WriteDone(IAsyncResult result) { //数据已经发送给了服务器 m_pipe.EndWrite(result); //异步的读取服务器的响应 byte[] data = new Byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotResponse, data); }
private void WriteDone(IAsyncResult result) { // The data was sent to the server m_pipe.EndWrite(result); // Asynchronously read the server's response Byte[] data = new Byte[1000]; m_pipe.BeginRead(data, 0, data.Length, GotResponse, 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 NamedPipeClientStream pipestream, Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback) { if (pipestream == null) { throw new ArgumentNullException("pipestream"); } return(pipestream.BeginRead(buffer, offset, count, callback, null)); }
public NamedPipe(string pipeName, int maxPipes = 10) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut); byte[] buf = new byte[1024]; pipeClient.BeginRead(buf, 0, 1024, new AsyncCallback(test), null); // NamedPipeServerStream pipeServer = new NamedPipeServerStream(".", pipeName, PipeDirection.InOut, numThreads); }
private void WriteDone(IAsyncResult result) { // Данные отправлены на сервер _namedPipeClient.EndWrite(result); // Асинхронное чтение ответа сервера var data = new byte[DefaultByteBufferLength]; _namedPipeClient.BeginRead(data, 0, data.Length, GotResponse, data); }
private void OnRead(IAsyncResult ar) { var bytesRead = _pipe.EndRead(ar); var str = Encoding.ASCII.GetString(_readBuffer, 0, bytesRead); _stringBuilder.Append(str); ProcessInBuffer(); _pipe.BeginRead(_readBuffer, 0, _readBuffer.Length, OnRead, null); }
public void Read_from_Server_Async() { if (clientStream.CanRead && clientStream.IsConnected) { clientStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 2); } else { close_pipe(); } }
public PipeClient() { PipeSt st = new PipeSt() { pipe = client, buffer = new byte[10240], packet = new PipeRecievePacket() }; client.Connect(2000); gar = client.BeginRead(st.buffer, 0, st.buffer.Length, ReadCallBack, st); }
// // Begin reading from the pipe // private void BeginRead(Message message) { try { //Console.WriteLine("BeginRead " + pipeName); pipeStream.BeginRead(bufferRead, 0, bufferRead.Length, EndReadCallBack, message); } catch (Exception ex) { Console.WriteLine("BeginRead error: " + ex.Message); } }
public Pipe(string pipeName) { pipeStream = new NamedPipeClientStream(".", App.CurrentApp.settings.pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough); pipeStream.Connect(); res = pipeStream.BeginRead(buffer, 0, 1, recieved, null); timer = new Timer(interval) { AutoReset = true }; timer.Elapsed += peek_workers; timer.Start(); }
/// <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 NamedPipeClientStream 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)); }
private void Connect(int timeout) { clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); try { clientStream.Connect(timeout); } catch (TimeoutException) { return; } clientStream.ReadMode = PipeTransmissionMode.Message; clientStream.BeginRead(buffer, 0, buffer.Length, ReadCompleted, null); }
private void BeginRead() { try { _client.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, null); } catch (Exception) { if (OnDisconnected != null) { OnDisconnected(this); } } }
private void StartReceivingData() { if (Pipe.IsConnected) { try { Pipe.BeginRead(InnerBuffer, 0, InnerBuffer.Length, new AsyncCallback(StartReceivingDataCallBack), null); } catch (Exception ex) { SetOnPipeException(ex); ShutdownClient(); } } }
/// <summary> /// start receiving from pipe /// </summary> private void startReceive() { try { m_pipeHandle.BeginRead(m_readBuffer, 0, m_options.m_numOfReadBytes, OnReadComplete, this); m_connected = true; m_options.m_callBackObj.OnConnected(this, IpcConnectStatus.SUCCESS); } catch (System.Exception ex) { Console.WriteLine(ex.Message + " >" + ex.StackTrace); Disconnect(); m_options.m_callBackObj.OnConnected(this, IpcConnectStatus.FAIL_READ_FAILED); } }
public void Read_from_Server_Async() { Log("Read_from_Server_Async"); if (clientStream.CanRead && clientStream.IsConnected) { Log("Read_from_Server_Async restart"); clientStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 2); clientStream.Flush(); } else { Log("Read_from_Server_Async closing pipe"); close_pipe(); } }