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 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; } }
private void OnReadFinished(IAsyncResult result) { var pipeState = (IPipeState)result.AsyncState; var readLength = _pipe.EndRead(result); if (_disposable.IsDisposed) { return; } var intermediateMessage = pipeState.Buffer.Take(readLength); pipeState.Message.AddRange(intermediateMessage); if (_pipe.IsMessageComplete) { var message = pipeState.Message.ToArray(); _messages.OnNext(message); pipeState.Message.Clear(); } if (_pipe.IsConnected) { _pipe.BeginRead(pipeState.Buffer, 0, pipeState.Buffer.Length, OnReadFinished, pipeState); } else { _pipe.BeginWaitForConnection(OnConnection, pipeState); } }
private void StartReceivingDataCallBack(IAsyncResult Ar) { try { int BytesReceived = Pipe.EndRead(Ar); if (BytesReceived <= 0) { Console.WriteLine("LESS THAN ZERO"); ClosePipeServer(); } else { MessageStore.Write(InnerBuffer, 0, BytesReceived); if (Pipe.IsMessageComplete) { Packet Message = PacketManager.GetPacket(MessageStore.ToArray(), 0); SetOnPipeReceived(Message); MessageStore.Position = 0; MessageStore.SetLength(0); } StartReceivingData(); } } catch (Exception ex) { SetOnPipeException(ex); ClosePipeServer(); } }
/// <summary> /// Handles the read event of the <see cref="NamedPipeServerStream"/> object. /// </summary> /// <param name="ar">The <see cref="IAsyncResult"/>s that contains readable information.</param> private void NamedPipeRead(IAsyncResult ar) { if (mPipedStream != null && ar.IsCompleted && mPipedStream.IsMessageComplete) { int length = mPipedStream.EndRead(ar); string cmdArgs = Encoding.Default.GetString( (byte[])ar.AsyncState , 0 , length); try { mPipedStream.Disconnect(); mPipedStream.BeginWaitForConnection( NamedPipeConnected , null); HandlePipedMessage(cmdArgs); } catch (Exception ex) { Logger.Error(ex.Message); } } }
private static void DataRead(IAsyncResult ar) { Console.WriteLine(">>> DataRead"); try { if (ar.IsCompleted) { // Terminate the read the read data from the buffer int bytesRead = myPipe.EndRead(ar); if (bytesRead > 0) { System.Text.ASCIIEncoding asciiEncoder = new System.Text.ASCIIEncoding(); string stringReadbuffer = asciiEncoder.GetString(readBuffer); char[] trimChars = new char[2] { '\0', '\n' }; Console.WriteLine(stringReadbuffer.TrimEnd(trimChars)); } } } catch (Exception e) { Console.WriteLine(e.Message); } // Create a new read buffer each loop so we have a fresh // read without including anything that was previously stored readBuffer = new byte[256]; Console.WriteLine("<<< DataRead"); }
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); }
private void OnReadAsync(IAsyncResult ar) { if (_pipeServer == null) { ReleaseServerReference(false); return; } int read; try { read = _pipeServer.EndRead(ar); } catch (Exception ex) { ReleaseServerReference(false); MessageBox.Show(ex.Message, "RpcServer", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (read == 0) { // pipe closed probably... Debug.WriteLine($"Pipe closed"); ReleaseServerReference(true); return; } Debug.WriteLine($"Read {read} bytes"); ProcessData(read); _pipeServer.BeginRead(_readBuffer, 0, _readBuffer.Length, OnReadAsync, null); }
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 GotRequest(IAsyncResult result) { int bytesRead = m_pipe.EndRead(result); var data = (byte[])result.AsyncState; data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); m_pipe.BeginWrite(data, 0, data.Length, WriteDone, 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 OnReceive(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, OnReceive, null); }
private void _gotRequest(IAsyncResult result) { //客户端向我们发送一个请求处理它 int bytesRead = m_pipe.EndRead(result); byte[] data = (byte[])result.AsyncState; //将字符转换为大写 data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); //将响应的异步地址发送给客户端 m_pipe.BeginWrite(data, 0, data.Length, _writeDone, null); }
private void Async_Read_Completed(IAsyncResult result) { namedPipeServerStream.EndRead(result); namedPipeServerStream.WaitForPipeDrain(); this.Server_Message = ASCIIEncoding.ASCII.GetString(read_buffer); this.Server_Message.Trim(); Console.WriteLine("Received from Client => " + this.Server_Message + " <=REnd"); // Read_from_Client_Async(); }
private void ReadCallback(IAsyncResult ar) { var readBytes = _server.EndRead(ar); if (readBytes > 0) { var message = (Message)ar.AsyncState; OnClientMessage?.Invoke(message.Buffer); } OnDisconnected(); }
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 }
//=================================================================== // 多重起動防止 //=================================================================== /// 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 GotRequest(IAsyncResult result) { // Обработка присланного клиентом запроса int bytesRead = _pipeServerStream.EndRead(result); var data = (byte[])result.AsyncState; // Мой сервер просто меняет регистр символов, // но вы можете вставить сюда любую вычислительную операцию data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray()); // Асинхронная отправка ответа клиенту _pipeServerStream.BeginWrite(data, 0, data.Length, WriteDone, null); }
private void processRead(IAsyncResult ar) { int len = 0; try { len = pipeServer.EndRead(ar); } catch (Exception) { } if (len > 0) { string args = UTF8Encoding.UTF8.GetString(buffer, 0, len); pipeServer.Close(); onArgs(args); pipeServer = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); pipeServer.BeginWaitForConnection(new AsyncCallback(processConnection), null); } }
/// <summary> /// This callback is called when the BeginRead operation is completed. /// We can arrive here whether the connection is valid or not /// </summary> private void EndReadCallBack(IAsyncResult result) { var readBytes = _pipeServer.EndRead(result); if (readBytes > 0) { var info = (Info)result.AsyncState; // Get the read bytes and append them info.StringBuilder.Append(_encoder.GetString(info.Buffer, 0, readBytes)); if (!_pipeServer.IsMessageComplete) // Message is not complete, continue reading { BeginRead(info); } else // Message is completed { // Finalize the received string and fire MessageReceivedEvent var message = info.StringBuilder.ToString().TrimEnd('\0'); OnMessageReceived(message); // Begin a new reading operation BeginRead(new Info()); } } else // When no bytes were read, it can mean that the client have been disconnected { if (!_isStopping) { lock (_lockingObject) { if (!_isStopping) { OnDisconnected(); // Disenno original, termina el NamedPipeServerStream cuando el cliente se desconecta // para Watchdog el pipeserver solo se termina cuando se termina el servicio // por lo que comienza a esperar conexiones de nuevo. //Stop(); if (_pipeServer.IsConnected) { _pipeServer.Disconnect(); } Start(); } } } } }
private void GotRequest(IAsyncResult result) { // The client sent us a request, process it. Int32 bytesRead = m_pipe.EndRead(result); Byte[] data = (Byte[])result.AsyncState; // 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 m_pipe.BeginWrite(data, 0, data.Length, WriteDone, null); }
void GotRequest(IAsyncResult result) { //客户端向我们发送了一个请求,处理它 Int32 byteRead = m_pipe.EndRead(result); byte[] data = (byte[])result.AsyncState; //我的示例服务器只是将所有字符更改为大写 //但是,你可以将这些代码更改为任何计算机限制的操作 Console.WriteLine("Client Request:" + Encoding.UTF8.GetString(data, 0, byteRead)); data = Encoding.UTF8.GetBytes( Encoding.UTF8.GetString(data, 0, byteRead).ToUpper().ToCharArray()); //将响应一步地发送给客户端 m_pipe.BeginWrite(data, 0, data.Length, WriteDone, null); }
/// <summary> /// End the asynchronous read operation on a connected named pipe. /// </summary> /// <param name="iAsyncResult"></param> private void _endRead(IAsyncResult iAsyncResult) { //Get the instance of the connection we're ending for AsyncPipeStateWrapper wrapper = iAsyncResult.AsyncState as AsyncPipeStateWrapper; NamedPipeServerStream connection = wrapper.NamedPipeServerStream; if (connection != null && connection.IsConnected) { try { //Get the length read int length = connection.EndRead(iAsyncResult); byte[] readBuffer = wrapper.Buffer; //If we have somethign read... if (length > 0) { byte[] destinationArray = new byte[length]; Array.Copy(readBuffer, 0, destinationArray, 0, length); //Deserialize the read object using (MemoryStream memStream = new MemoryStream(readBuffer)) { //Still figuring out why this excepts try { SbStateObject stateObject = Serializer.Deserialize <SbStateObject>(memStream); //Cool, we have ourselves our very own SbStateObject. Fire the event. if (SbStateObjectReceived != null) { SbStateObjectReceived(this, new SbStateObjectEventArgs(stateObject, connection)); } } catch (ProtoException) { } } } //lock the connection and begin reading lock (connection) { //Sanitize the read buffer. FFS, examples... readBuffer = new byte[SIZE_BUFFER]; connection.BeginRead(readBuffer, 0, SIZE_BUFFER, new AsyncCallback(this._endRead), new AsyncPipeStateWrapper(connection, readBuffer)); } } catch (Exception) { } } }
private void AsyncReadMessageCallback(IAsyncResult result) { _pipe.EndRead(result); if (!_pipeMessage.IsNullOrEmpty()) { OnMessageReceived(_pipeMessage.Message); } if (_pipe.IsConnected) { BeginRead(); } else { Close(); Open(); } }
private void EndReadCallBack(IAsyncResult result) { Console.WriteLine(">>> IS :EndReadCallBack ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); var readBytes = pipeServer.EndRead(result); if (readBytes > 0) { var info = (Message)result.AsyncState; // Get the read bytes and append them info.StringBuilder.Append(Encoding.UTF8.GetString(info.Buffer, 0, readBytes)); if (!pipeServer.IsMessageComplete) // Message is not complete, continue reading { BeginRead(info); } else // Message is completed { // Finalize the received string and fire MessageReceivedEvent var message = info.StringBuilder.ToString().TrimEnd('\0'); OnMessageReceived(message); // Begin a new reading operation BeginRead(new Message()); } } else // When no bytes were read, it can mean that the client have been disconnected { Console.WriteLine("ReadBytes are less then or equal to 0"); if (!isStopping) { lock (lockingObject) { if (!isStopping) { OnDisconnected(); Stop(); } } } } Console.WriteLine("<<< IS :EndReadCallBack ThreadId: {0}", Thread.CurrentThread.ManagedThreadId); }
private void OnHeader(IAsyncResult result) { if (!ProcessCount(pipe_.EndRead(result), 8)) { return; } var hdrBytes = new Bytes((byte[])result.AsyncState); uint msgLength = hdrBytes.ReadUInt32(); int msgId = hdrBytes.ReadInt32(); var msgData = new MessageData { buffer = new byte[msgLength], length = msgLength, msgId = msgId }; pipe_.BeginRead(msgData.buffer, 0, (int)msgLength, OnMessage, msgData); }
private static void StartServerBytes() { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message); int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect pipeServer.WaitForConnection(); while (pipeServer.IsConnected) { StringBuilder sb = new StringBuilder(); do { var buffer = new byte[10]; AutoResetEvent manualResetEvent = new AutoResetEvent(false); pipeServer.BeginRead(buffer, 0, buffer.Length, (st) => { pipeServer.EndRead(st); manualResetEvent.Set(); }, null); manualResetEvent.WaitOne(); sb.Append(UnicodeEncoding.Default.GetString(buffer)); }while (!pipeServer.IsMessageComplete); Console.WriteLine(sb.ToString()); Console.Write("Ready: "); string readline; do { readline = Console.ReadLine(); } while (string.IsNullOrEmpty(readline)); byte[] resp = UnicodeEncoding.Default.GetBytes(readline); pipeServer.Write(resp, 0, resp.Length); } pipeServer.Close(); }
private void callbackRead(IAsyncResult result) { int count = _stream.EndRead(result); if (count == 0) { if (_stream.IsConnected) { _stream.Disconnect(); } _stream.BeginWaitForConnection(new AsyncCallback(callbackConnection), null); } else { _stream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(callbackRead), null); string command = Encoding.UTF8.GetString(_buffer, 0, count - 1); Shell.Main.ProcessCmdLine("|", command); } }
private void GetRequest(IAsyncResult result) { Int32 br = m_Pipe.EndRead(result); if (br == 0) { Console.WriteLine(String.Format("管道已关闭:{0}", m_Pipe.GetImpersonationUserName())); m_Pipe.Close(); } else { Byte[] data = (Byte[])result.AsyncState; String str = Encoding.UTF8.GetString(data, 0, br).ToUpper(); Console.WriteLine(String.Format("接收到客户端数据:{0}", str)); data = Encoding.UTF8.GetBytes(str); m_Pipe.BeginWrite(data, 0, data.Length, WriteDone, null); m_Pipe.BeginRead(data, 0, data.Length, GetRequest, data); } }