/// <summary> /// WaitForMessage - have the server wait for a message /// </summary> /// <returns>a non-null MessageStream if it got a message, null if timed out or error /// </returns> public MemoryStream WaitForMessage() { bool fullyRead = false; string errMsg = ""; int errCode = 0; // They want to talk to us, read their messages and write replies MemoryStream receiveStream = new MemoryStream(); byte[] buffer = new byte[_receiveBufferSize]; byte[] _numReadWritten = new byte[4]; // Need to read the whole message and put it in one message byte buffer do { // Read the response from the pipe if (!NamedPipeInterop.ReadFile( _handle, // Pipe handle buffer, // Buffer to receive reply (uint)_receiveBufferSize, // Size of buffer _numReadWritten, // Number of bytes read 0)) // Not overlapped { // Failed, not just more data to come errCode = Marshal.GetLastWin32Error( ); if (errCode != NamedPipeInterop.ERROR_MORE_DATA) { break; } else { errMsg = string.Format("Could not read from pipe with error {0}", errCode); Trace.WriteLine(errMsg); throw new Win32Exception(errCode, errMsg); } } else { // We succeeded and no more data is coming fullyRead = true; } // Concat the message bytes to the stream receiveStream.Write(buffer, 0, buffer.Length); } while (!fullyRead); // Return the message we received if any if (receiveStream.Length > 0) { return(receiveStream); } else // Didn't receive anything { return(null); } }
/// <summary> /// CreatePipe - create the named pipe /// </summary> /// <returns>true is pipe created</returns> public bool CreatePipe() { // Make a named pipe in message mode _handle = NamedPipeInterop.CreateNamedPipe(_pipeName, NamedPipeInterop.PIPE_ACCESS_DUPLEX, NamedPipeInterop.PIPE_TYPE_MESSAGE | NamedPipeInterop.PIPE_READMODE_MESSAGE | NamedPipeInterop.PIPE_WAIT, NamedPipeInterop.PIPE_UNLIMITED_INSTANCES, PIPE_SERVER_BUFFER_SIZE, PIPE_SERVER_BUFFER_SIZE, NamedPipeInterop.NMPWAIT_WAIT_FOREVER, IntPtr.Zero); // Make sure we got a good one if (_handle.IsInvalid) { Debug.WriteLine("Could not create the pipe (" + _pipeName + ") - os returned " + Marshal.GetLastWin32Error()); return(false); } return(true); }
/// <summary> /// WaitForClientConnect - wait for a client to connect to this pipe /// </summary> /// <returns>true if connected, false if timed out</returns> public bool WaitForClientConnect() { // Wait for someone to talk to us. return(NamedPipeInterop.ConnectNamedPipe(_handle, IntPtr.Zero)); }