Merge pull request #900 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / class / System / System.Net.Sockets / TcpListener.cs
1 // TcpListener.cs
2 //
3 // Authors:
4 //    Phillip Pearson (pp@myelin.co.nz)
5 //    Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //        Patrik Torstensson
7 //    Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 //    Marek Safar (marek.safar@gmail.com)
9
10 //
11 // Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
12 //
13 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
14 // (c) 2004-2006 Novell, Inc.
15 // Copyright 2011 Xamarin Inc.
16 //
17
18 //
19 // Permission is hereby granted, free of charge, to any person obtaining
20 // a copy of this software and associated documentation files (the
21 // "Software"), to deal in the Software without restriction, including
22 // without limitation the rights to use, copy, modify, merge, publish,
23 // distribute, sublicense, and/or sell copies of the Software, and to
24 // permit persons to whom the Software is furnished to do so, subject to
25 // the following conditions:
26 // 
27 // The above copyright notice and this permission notice shall be
28 // included in all copies or substantial portions of the Software.
29 // 
30 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
34 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
35 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
36 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 //
38
39 using System;
40 using System.Net;
41 #if NET_4_5
42 using System.Threading.Tasks;
43 #endif
44
45 namespace System.Net.Sockets
46 {
47         /// <remarks>
48         /// A slightly more abstracted way to listen for incoming
49         /// network connections than a Socket.
50         /// </remarks>
51         public class TcpListener
52         {
53                 // private data
54                 
55                 bool active;
56                 Socket server;
57                 EndPoint savedEP;
58                 
59                 // constructor
60
61                 /// <summary>
62                 /// Some code that is shared between the constructors.
63                 /// </summary>
64                 private void Init (AddressFamily family, EndPoint ep)
65                 {
66                         active = false;
67                         server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
68                         savedEP = ep;
69                 }
70                 
71                 /// <summary>
72                 /// Constructs a new TcpListener to listen on a specified port
73                 /// </summary>
74                 /// <param name="port">The port to listen on, e.g. 80 if you 
75                 /// are a web server</param>
76                 [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
77                 public TcpListener (int port)
78                 {
79                         if (port < 0 || port > 65535)
80                                 throw new ArgumentOutOfRangeException ("port");
81
82                         Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
83                 }
84
85                 /// <summary>
86                 /// Constructs a new TcpListener with a specified local endpoint
87                 /// </summary>
88                 /// <param name="local_end_point">The endpoint</param>
89                 public TcpListener (IPEndPoint localEP)
90                 {
91                         if (localEP == null)
92                                 throw new ArgumentNullException ("localEP");
93
94                         Init (localEP.AddressFamily, localEP);
95                 }
96                 
97                 /// <summary>
98                 /// Constructs a new TcpListener, listening on a specified port
99                 /// and IP (for use on a multi-homed machine)
100                 /// </summary>
101                 /// <param name="listen_ip">The IP to listen on</param>
102                 /// <param name="port">The port to listen on</param>
103                 public TcpListener (IPAddress localaddr, int port)
104                 {
105                         if (localaddr == null)
106                                 throw new ArgumentNullException ("localaddr");
107
108                         if (port < 0 || port > 65535)
109                                 throw new ArgumentOutOfRangeException ("port");
110
111                         Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
112                 }
113
114
115                 // properties
116
117                 /// <summary>
118                 /// A flag that is 'true' if the TcpListener is listening,
119                 /// or 'false' if it is not listening
120                 /// </summary>
121                 protected bool Active
122                 {
123                         get { return active; }
124                 }
125
126                 /// <summary>
127                 /// The local end point
128                 /// </summary>
129                 public EndPoint LocalEndpoint
130                 {
131                         get { 
132                                 if (active)
133                                         return server.LocalEndPoint;
134
135                                 return savedEP; 
136                         }
137                 }
138                 
139                 /// <summary>
140                 /// The listening socket
141                 /// </summary>
142                 public Socket Server
143                 {
144                         get { return server; }
145                 }
146
147                 /// <summary>
148                 /// Specifies whether the TcpListener allows only one
149                 /// underlying socket to listen to a specific port
150                 /// </summary>
151 #if TARGET_JVM
152                 [MonoNotSupported ("Not supported as Socket.ExclusiveAddressUse is not supported")]
153 #endif
154                 public bool ExclusiveAddressUse
155                 {
156                         get {
157                                 if (server == null) {
158                                         throw new ObjectDisposedException (GetType ().ToString ());
159                                 }
160                                 if (active) {
161                                         throw new InvalidOperationException ("The TcpListener has been started");
162                                 }
163
164                                 return(server.ExclusiveAddressUse);
165                         }
166                         set {
167                                 if (server == null) {
168                                         throw new ObjectDisposedException (GetType ().ToString ());
169                                 }
170                                 if (active) {
171                                         throw new InvalidOperationException ("The TcpListener has been started");
172                                 }
173
174                                 server.ExclusiveAddressUse = value;
175                         }
176                 }
177                 
178                 // methods
179
180                 /// <summary>
181                 /// Accepts a pending connection
182                 /// </summary>
183                 /// <returns>A Socket object for the new connection</returns>
184                 public Socket AcceptSocket ()
185                 {
186                         if (!active)
187                                 throw new InvalidOperationException ("Socket is not listening");
188
189                         return server.Accept();
190                 }
191                 
192                 /// <summary>
193                 /// Accepts a pending connection
194                 /// </summary>
195                 /// <returns>A TcpClient
196                 /// object made from the new socket.</returns>
197                 public TcpClient AcceptTcpClient ()
198                 {
199                         if (!active)
200                                 throw new InvalidOperationException ("Socket is not listening");
201
202                         Socket clientSocket = server.Accept ();
203
204                         TcpClient client = new TcpClient(clientSocket);
205                         
206                         return client;
207                 }
208                 
209                 /// <summary>
210                 /// Destructor - stops the listener listening
211                 /// </summary>
212                 ~TcpListener ()
213                 {
214                         if (active)
215                                 Stop();
216                 }
217         
218                 /// <returns>
219                 /// Returns 'true' if there is a connection waiting to be accepted
220                 /// with AcceptSocket() or AcceptTcpClient().
221                 /// </returns>
222                 public bool Pending ()
223                 {
224                         if (!active)
225                                 throw new InvalidOperationException ("Socket is not listening");
226
227                         return server.Poll(0, SelectMode.SelectRead);
228                 }
229                 
230                 /// <summary>
231                 /// Tells the TcpListener to start listening.
232                 /// </summary>
233                 public void Start ()
234                 {
235                         // MS: sets Listen to Int32.MaxValue
236                         this.Start (5);
237                         // According to the man page some BSD and BSD-derived
238                         // systems limit the backlog to 5.  This should really be
239                         // configurable though
240                 }
241
242                 /// <summary>
243                 /// Tells the TcpListener to start listening for max number
244                 /// of pending connections.
245                 /// </summary>
246
247                 public void Start (int backlog)
248                 {
249                         if (active) {
250                                 return;
251                         }
252                         if (server == null) {
253                                 throw new InvalidOperationException ("Invalid server socket");
254                         }
255                         
256                         server.Bind (savedEP);
257                         server.Listen (backlog);
258                         active = true;
259                 }
260
261                 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
262                                                        object state)
263                 {
264                         if (server == null) {
265                                 throw new ObjectDisposedException (GetType ().ToString ());
266                         }
267                         
268                         return(server.BeginAccept (callback, state));
269                 }
270                 
271                 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
272                 {
273                         if (server == null) {
274                                 throw new ObjectDisposedException (GetType ().ToString ());
275                         }
276                         
277                         return(server.BeginAccept (callback, state));
278                 }
279                 
280                 public Socket EndAcceptSocket (IAsyncResult asyncResult) 
281                 {
282                         return(server.EndAccept (asyncResult));
283                 }
284                 
285                 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
286                 {
287                         Socket clientSocket = server.EndAccept (asyncResult);
288                         TcpClient client = new TcpClient (clientSocket);
289                         
290                         return(client);
291                 }
292                 
293                 /// <summary>
294                 /// Tells the TcpListener to stop listening and dispose
295                 /// of all managed resources.
296                 /// </summary>
297                 public void Stop ()
298                 {
299                         if (active) 
300                         {
301                                 server.Close ();
302                                 server = null;
303                         }
304
305                         Init (AddressFamily.InterNetwork, savedEP);
306                 }
307
308 #if NET_4_5
309                 public Task<Socket> AcceptSocketAsync ()
310                 {
311                         return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
312                 }
313
314                 public Task<TcpClient> AcceptTcpClientAsync ()
315                 {
316                         return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
317                 }
318 #endif
319         }
320 }