コード例 #1
0
ファイル: IpcPipe.cs プロジェクト: wwwyfjp/EpLibrary.cs
        /// <summary>
        /// Write data to the pipe
        /// </summary>
        /// <param name="data">the data to write</param>
        /// <param name="offset">offset to start write from given data</param>
        /// <param name="dataByteSize">byte size of the data to write</param>
        public void Write(byte[] data, int offset, int dataByteSize)
        {
            if (dataByteSize > m_options.m_numOfWriteBytes)
            {
                throw new ArgumentException();
            }
            PipeWriteElem elem = new PipeWriteElem(data, offset, dataByteSize);

            lock (m_writeQueue)
            {
                if (m_writeQueue.Count > 0)
                {
                    m_writeQueue.Enqueue(elem);
                }
                else
                {
                    try
                    {
                        m_pipeHandle.BeginWrite(elem.m_data, 0, elem.m_dataSize, OnWriteComplete, this);
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex.Message + " >" + ex.StackTrace);
                        if (IsConnectionAlive())
                        {
                            KillConnection();
                        }
                    }
                }
            }
        }
コード例 #2
0
            private void send()
            {
                _isWriting = true;

                int charCount, byteCount;

                if (((_currentMsg.Length - _pos) * 4) + _msgEnd.Length > _buffer.Length)
                {
                    charCount = _buffer.Length / 4;
                    byteCount = Encoding.UTF8.GetBytes(_currentMsg, _pos, charCount, _buffer, 0);
                    _pos     += charCount;
                }
                else
                {
                    charCount = _currentMsg.Length - _pos;
                    byteCount = Encoding.UTF8.GetBytes(_currentMsg, _pos, charCount, _buffer, 0);
                    _pos      = -1;
                    for (int i = 0; i < _msgEnd.Length; i++)
                    {
                        _buffer[byteCount++] = _msgEnd[i];
                    }
                }

                _stream.BeginWrite(_buffer, 0, byteCount, new AsyncCallback(callbackWrite), null);
            }
コード例 #3
0
        /// <summary>
        /// Send a UiStateObject to a specified session via named pipe.
        /// </summary>
        /// <param name="uiStateObject"></param>
        public void SendUiStateObject(string session, UiStateObject uiStateObject)
        {
            //If we've got a connection for the passed session and it's an active connection...
            if (_sessions_namedPipes.ContainsKey(session))
            {
                //Get lock object on the connection
                NamedPipeServerStream connection = _sessions_namedPipes[session];
                lock (connection)
                {
                    //Check if it's connected, if so begin the write.
                    if (connection.IsConnected)
                    {
                        byte[] message;
                        //Get the bytes from the object...
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            Serializer.Serialize <UiStateObject>(memStream, uiStateObject);
                            message = memStream.ToArray();
                        }

                        //Start the write
                        connection.BeginWrite(message, 0, message.Length,
                                              new AsyncCallback(_endWrite), new AsyncPipeStateWrapper(connection, null));
                    }
                }
            }
        }
コード例 #4
0
        private void WriteLine(NamedPipeServerStream pipe, string text)
        {
            PipeSendPacket pipeSend = new PipeSendPacket();

            BinaryUtils.Write(pipeSend.Data, text);
            byte[] data = pipeSend.PackData();
            pipe.BeginWrite(data, 0, data.Length, null, null);
        }
コード例 #5
0
        private void DoSendReport(IList <StatusReportItem> report)
        {
            string text = JsonConvert.SerializeObject(report);

            Logger.Debug($"Sending result report:\n{text}");
            byte[] buffer = new UTF8Encoding().GetBytes(text);
            _server.BeginWrite(buffer, 0, buffer.Length, OnWrite, null);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        /// <summary>
        /// Extends BeginWrite so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// pipestream.BeginWrite(buffer, offset, count, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginWrite(this NamedPipeServerStream pipestream, Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback)
        {
            if (pipestream == null)
            {
                throw new ArgumentNullException("pipestream");
            }

            return(pipestream.BeginWrite(buffer, offset, count, callback, null));
        }
コード例 #8
0
            public override void Write(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);

                    stream.BeginWrite(buf, off, len, asyncResult =>
                    {
                        try
                        {
                            if (stream != null)
                            {
                                stream.EndWrite(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
                {
                    stream.Write(buf, off, len);
                }
#else
                stream.Write(buf, off, len);
#endif
            }
コード例 #9
0
 void waveIn_DataAvailable(object sender, WaveInEventArgs e)
 {
     try
     {
         _server.BeginWrite(e.Buffer, 0, e.BytesRecorded, WriteCallback, new Object());
     }
     catch (Exception)
     {
         Ooops();
     }
 }
コード例 #10
0
    private void BeginWriteCommand(CommandMessage command)
    {
        if (CommandStream != null && CommandStream.IsConnected)
        {
            var commandBytes = CommandMessage.ToBytes(command);

            CommandStream.WaitForPipeDrain();

            CommandStream.BeginWrite(commandBytes, 0, commandBytes.Length, WriteCommandAsyncCallback, null);
        }
    }
コード例 #11
0
ファイル: Program.cs プロジェクト: geniussheep/MyTest
        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);
        }
コード例 #12
0
    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
    }
コード例 #13
0
 private void BeginWrite(Info info)
 {
     try
     {
         _pipeServer.BeginWrite(info.Buffer, 0, BufferSize, EndReadCallBack, info);
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
         throw;
     }
 }
コード例 #14
0
ファイル: PipeServer.cs プロジェクト: simple555a/DotNetAppDev
        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);
        }
コード例 #15
0
ファイル: PipeServer.cs プロジェクト: tomAsh00/Pipe.Net
 public void SendMessage(string message)
 {
     if (_pipe.IsConnected)
     {
         Connected = true;
         var msg = new PipeMessage(message);
         _pipe.BeginWrite(msg.MessageBytes, 0, PipeMessage.MessageBufferSize, AsyncBeginWriteCallback, _pipe);
     }
     else
     {
         Connected = false;
         throw new Exception("No client connected to pipe.");
     }
 }
コード例 #16
0
        private static void SendBytes(byte[] bytes)
        {
            if (_client != null)
            {
                var bytesSize   = BitConverter.GetBytes(bytes.Length);
                var bytesToSend = new byte[bytes.Length + sizeof(int)];

                Buffer.BlockCopy(bytesSize, 0, bytesToSend, 0, bytesSize.Length);
                Buffer.BlockCopy(bytes, 0, bytesToSend, sizeof(int), bytes.Length);

                _client.BeginWrite(bytesToSend, 0, bytesToSend.Length,
                                   delegate(IAsyncResult ar) { _client.EndWrite(ar); }, null);
            }
        }
コード例 #17
0
        /// <summary>
        /// Extends BeginWrite so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// pipestream.BeginWrite(buffer, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginWrite(this NamedPipeServerStream pipestream, Byte[] buffer, AsyncCallback callback)
        {
            if (pipestream == null)
            {
                throw new ArgumentNullException("pipestream");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            return(pipestream.BeginWrite(buffer, 0, buffer.Length, callback));
        }
コード例 #18
0
        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);
        }
コード例 #19
0
        public async Task <PointerData> QueryFunctionPointerData(long pointer)
        {
            if (_pipeServer == null)
            {
                throw new InvalidOperationException("Not connected.");
            }

            var request = new Request(Interlocked.Increment(ref _nextRequestId));

            Debug.WriteLine($"QueryFunctionPointerData, rid: {request.Id}");

            _requestsLock.EnterWriteLock();
            try
            {
                _requests.Add(request.Id, request);
            }
            finally
            {
                _requestsLock.ExitWriteLock();
            }

            using (var ms = new MemoryStream(4096))
                using (var bw = new BinaryWriter(ms, Encoding.UTF8, true))
                {
                    bw.Write(3); // command - request function pointer data
                    bw.Write(request.Id);
                    bw.Write(pointer);

                    Interlocked.Increment(ref _outstandingIO);
                    _pipeServer.BeginWrite(ms.GetBuffer(), 0, (int)bw.BaseStream.Length, OnWriteAsync, null);
                }

            await request.Wait();

            Debug.WriteLine($"QueryFunctionPointerData REQUEST COMPLETED rid: {request.Id}");

            using (request)
            {
                using (var ms = new MemoryStream(request.Response, 0, request.ResponseLength, false))
                    using (var br = new BinaryReader(ms, Encoding.UTF8, true))
                    {
                        br.ReadInt64(); // pointer
                        var functionName = br.BaseStream.ReadNullTerminatedString(256);

                        return(new PointerData(pointer, functionName));
                    }
            }
        }
コード例 #20
0
        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);
        }
コード例 #21
0
ファイル: Pipe.cs プロジェクト: stealzy/DataServer
        private void ReadCallback(IAsyncResult ar, NamedPipeServerStream stream, byte[] buf)
        {
            string s = Encoding.ASCII.GetString(buf).TrimEnd(Encoding.ASCII.GetChars(new byte[] { 0 }));

            if (String.IsNullOrEmpty(s))
            {
                stream.Close();
                return;
            }
            // Console.WriteLine(s);byte[] msg = Encoding.UTF8.GetBytes(put);
            var mess = Encoding.ASCII.GetBytes("Received");

            stream.BeginWrite(mess, 0, mess.Length, i => { }, new object());
            buf = new byte[1024];
            stream.BeginRead(buf, 0, buf.Length, arg => ReadCallback(arg, stream, buf), new object());
        }
コード例 #22
0
        public void Write_to_Client_Async(string message)
        {
            if (namedPipeServerStream != null)
            {
                if (namedPipeServerStream.CanWrite && namedPipeServerStream.IsConnected)
                {
                    namedPipeServerStream.WaitForPipeDrain();
                    ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer, 0);

                    namedPipeServerStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 2);
                    namedPipeServerStream.Flush();
                }
                else
                {
                    close_pipe();
                }
            }
        }
コード例 #23
0
ファイル: Pipe.cs プロジェクト: stealzy/DataServer
 private void Loop(NamedPipeServerStream stream)
 {
     try
     {
         while (true)
         {
             if (sendmessage != "")
             {
                 // stream.BeginRead(buf, 0, buf.Length, ar=> ReadCallback(ar, stream, buf), new object());
                 byte[] mess = Encoding.UTF8.GetBytes(sendmessage + "/n/r");
                 mes.add("пишем " + name);
                 stream.BeginWrite(mess, 0, mess.Length, i => { }, new object());
                 Thread.Sleep(500);
             }
             Thread.Sleep(100);
         }
     }
     catch { }
 }
コード例 #24
0
        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);
            }
        }
コード例 #25
0
        bool Yaz(NamedPipeServerStream Akış, int ZamanAşımı_msn, byte[] Girdi, int Adet)
        {
            try
            {
                int          Tik   = Environment.TickCount + ZamanAşımı_msn;
                IAsyncResult Döngü = Akış.BeginWrite(Girdi, 0, Adet, null, null);

                while (Environment.TickCount < Tik && !Döngü.IsCompleted)
                {
                    Thread.Sleep(2);
                }
                if (Döngü.IsCompleted)
                {
                    Akış.EndWrite(Döngü);
                    return(true);
                }
            }
            catch (Exception) { }
            return(false);
        }
コード例 #26
0
            public override void Write(byte[] buf, int off, int len)
            {
                if (stream == null)
                {
                    throw new TTransportException(TTransportException.ExceptionType.NotOpen);
                }

                // if necessary, send the data in chunks
                // there's a system limit around 0x10000 bytes that we hit otherwise
                // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section."
                var nBytes = Math.Min(len, 15 * 4096);  // 16 would exceed the limit

                while (nBytes > 0)
                {
                    if (asyncMode)
                    {
                        Exception eOuter = null;
                        var       evt    = new ManualResetEvent(false);

                        stream.BeginWrite(buf, off, nBytes, asyncResult =>
                        {
                            try
                            {
                                if (stream != null)
                                {
                                    stream.EndWrite(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, e);
                                }
                            }
                            evt.Set();
                        }, null);

                        evt.WaitOne();

                        if (eOuter != null)
                        {
                            throw eOuter; // rethrow exception
                        }
                    }
                    else
                    {
                        stream.Write(buf, off, nBytes);
                    }

                    off   += nBytes;
                    len   -= nBytes;
                    nBytes = Math.Min(len, nBytes);
                }
            }
コード例 #27
0
 public void Send(byte[] data)
 {
     _pipe.BeginWrite(data, 0, data.Length, OnWriteFinished, null);
 }