2 // System.Runtime.Remoting.Channels.Ipc.Win32.NamedPipeListener.cs
4 // Author: Robert Jordan (robertj@gmx.net)
6 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Runtime.InteropServices;
34 namespace System.Runtime.Remoting.Channels.Ipc.Win32
37 /// Listens for connections from local local Named Pipe clients.
39 internal class NamedPipeListener
41 const uint DefaultBufferSize = 4096;
42 readonly string pipeName;
46 get { return pipeName; }
50 /// Creates a new listener with the local local Named Pipe name obtained form the specified UID.
52 /// <param name="uid">The UID.</param>
53 public NamedPipeListener(Guid uid)
54 : this(uid.ToString("N"))
59 /// Creates a new listener with the specified name.
61 /// <param name="pipeName">The pipe name omiting the leading <c>\\.\pipe\</c></param>
62 public NamedPipeListener(string pipeName)
64 this.pipeName = NamedPipeHelper.FormatPipeName(pipeName);
68 /// Accepts a pending connection request
71 /// Accept is a blocking method that returns a NamedPipeSocket you can use to send and receive data.
73 /// <returns>The NamedPipeSocket.</returns>
74 public NamedPipeSocket Accept()
76 IntPtr hPipe = NamedPipeHelper.CreateNamedPipe(
78 NamedPipeHelper.PIPE_ACCESS_DUPLEX,
79 NamedPipeHelper.PIPE_TYPE_MESSAGE
80 | NamedPipeHelper.PIPE_READMODE_MESSAGE
81 | NamedPipeHelper.PIPE_WAIT,
82 NamedPipeHelper.PIPE_UNLIMITED_INSTANCES,
85 NamedPipeHelper.NMPWAIT_USE_DEFAULT_WAIT,
89 if (hPipe.ToInt32() == NamedPipeHelper.INVALID_HANDLE_VALUE)
91 throw new NamedPipeException();
94 bool canConnect = NamedPipeHelper.ConnectNamedPipe(hPipe, IntPtr.Zero);
95 int lastError = Marshal.GetLastWin32Error();
96 if (!canConnect && lastError == NamedPipeHelper.ERROR_PIPE_CONNECTED)
101 return new NamedPipeSocket(hPipe);
105 NamedPipeHelper.CloseHandle(hPipe);
106 throw new NamedPipeException(lastError);