[sgen] Untag the vtable during concurrent mark
[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 using System.Threading.Tasks;
42
43 namespace System.Net.Sockets
44 {
45         /// <remarks>
46         /// A slightly more abstracted way to listen for incoming
47         /// network connections than a Socket.
48         /// </remarks>
49         public class TcpListener
50         {
51                 // private data
52                 
53                 bool active;
54                 Socket server;
55                 EndPoint savedEP;
56                 
57                 // constructor
58
59                 /// <summary>
60                 /// Some code that is shared between the constructors.
61                 /// </summary>
62                 private void Init (AddressFamily family, EndPoint ep)
63                 {
64                         active = false;
65                         server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
66                         savedEP = ep;
67                 }
68                 
69                 /// <summary>
70                 /// Constructs a new TcpListener to listen on a specified port
71                 /// </summary>
72                 /// <param name="port">The port to listen on, e.g. 80 if you 
73                 /// are a web server</param>
74                 [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
75                 public TcpListener (int port)
76                 {
77                         if (port < 0 || port > 65535)
78                                 throw new ArgumentOutOfRangeException ("port");
79
80                         Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
81                 }
82
83                 /// <summary>
84                 /// Constructs a new TcpListener with a specified local endpoint
85                 /// </summary>
86                 /// <param name="local_end_point">The endpoint</param>
87                 public TcpListener (IPEndPoint localEP)
88                 {
89                         if (localEP == null)
90                                 throw new ArgumentNullException ("localEP");
91
92                         Init (localEP.AddressFamily, localEP);
93                 }
94                 
95                 /// <summary>
96                 /// Constructs a new TcpListener, listening on a specified port
97                 /// and IP (for use on a multi-homed machine)
98                 /// </summary>
99                 /// <param name="listen_ip">The IP to listen on</param>
100                 /// <param name="port">The port to listen on</param>
101                 public TcpListener (IPAddress localaddr, int port)
102                 {
103                         if (localaddr == null)
104                                 throw new ArgumentNullException ("localaddr");
105
106                         if (port < 0 || port > 65535)
107                                 throw new ArgumentOutOfRangeException ("port");
108
109                         Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
110                 }
111
112
113                 // properties
114
115                 /// <summary>
116                 /// A flag that is 'true' if the TcpListener is listening,
117                 /// or 'false' if it is not listening
118                 /// </summary>
119                 protected bool Active
120                 {
121                         get { return active; }
122                 }
123
124                 /// <summary>
125                 /// The local end point
126                 /// </summary>
127                 public EndPoint LocalEndpoint
128                 {
129                         get { 
130                                 if (active)
131                                         return server.LocalEndPoint;
132
133                                 return savedEP; 
134                         }
135                 }
136                 
137                 /// <summary>
138                 /// The listening socket
139                 /// </summary>
140                 public Socket Server
141                 {
142                         get { return server; }
143                 }
144
145                 /// <summary>
146                 /// Specifies whether the TcpListener allows only one
147                 /// underlying socket to listen to a specific port
148                 /// </summary>
149                 public bool ExclusiveAddressUse
150                 {
151                         get {
152                                 if (server == null) {
153                                         throw new ObjectDisposedException (GetType ().ToString ());
154                                 }
155                                 if (active) {
156                                         throw new InvalidOperationException ("The TcpListener has been started");
157                                 }
158
159                                 return(server.ExclusiveAddressUse);
160                         }
161                         set {
162                                 if (server == null) {
163                                         throw new ObjectDisposedException (GetType ().ToString ());
164                                 }
165                                 if (active) {
166                                         throw new InvalidOperationException ("The TcpListener has been started");
167                                 }
168
169                                 server.ExclusiveAddressUse = value;
170                         }
171                 }
172                 
173                 // methods
174
175                 /// <summary>
176                 /// Accepts a pending connection
177                 /// </summary>
178                 /// <returns>A Socket object for the new connection</returns>
179                 public Socket AcceptSocket ()
180                 {
181                         if (!active)
182                                 throw new InvalidOperationException ("Socket is not listening");
183
184                         return server.Accept();
185                 }
186                 
187                 /// <summary>
188                 /// Accepts a pending connection
189                 /// </summary>
190                 /// <returns>A TcpClient
191                 /// object made from the new socket.</returns>
192                 public TcpClient AcceptTcpClient ()
193                 {
194                         if (!active)
195                                 throw new InvalidOperationException ("Socket is not listening");
196
197                         Socket clientSocket = server.Accept ();
198
199                         TcpClient client = new TcpClient(clientSocket);
200                         
201                         return client;
202                 }
203                 
204                 /// <summary>
205                 /// Destructor - stops the listener listening
206                 /// </summary>
207                 ~TcpListener ()
208                 {
209                         if (active)
210                                 Stop();
211                 }
212         
213                 /// <returns>
214                 /// Returns 'true' if there is a connection waiting to be accepted
215                 /// with AcceptSocket() or AcceptTcpClient().
216                 /// </returns>
217                 public bool Pending ()
218                 {
219                         if (!active)
220                                 throw new InvalidOperationException ("Socket is not listening");
221
222                         return server.Poll(0, SelectMode.SelectRead);
223                 }
224                 
225                 /// <summary>
226                 /// Tells the TcpListener to start listening.
227                 /// </summary>
228                 public void Start ()
229                 {
230                         // MS: sets Listen to Int32.MaxValue
231                         this.Start (5);
232                         // According to the man page some BSD and BSD-derived
233                         // systems limit the backlog to 5.  This should really be
234                         // configurable though
235                 }
236
237                 /// <summary>
238                 /// Tells the TcpListener to start listening for max number
239                 /// of pending connections.
240                 /// </summary>
241
242                 public void Start (int backlog)
243                 {
244                         if (active) {
245                                 return;
246                         }
247                         if (server == null) {
248                                 throw new InvalidOperationException ("Invalid server socket");
249                         }
250                         
251                         server.Bind (savedEP);
252                         server.Listen (backlog);
253                         active = true;
254                 }
255
256                 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
257                                                        object state)
258                 {
259                         if (server == null) {
260                                 throw new ObjectDisposedException (GetType ().ToString ());
261                         }
262                         
263                         return(server.BeginAccept (callback, state));
264                 }
265                 
266                 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
267                 {
268                         if (server == null) {
269                                 throw new ObjectDisposedException (GetType ().ToString ());
270                         }
271                         
272                         return(server.BeginAccept (callback, state));
273                 }
274                 
275                 public Socket EndAcceptSocket (IAsyncResult asyncResult) 
276                 {
277                         return(server.EndAccept (asyncResult));
278                 }
279                 
280                 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
281                 {
282                         Socket clientSocket = server.EndAccept (asyncResult);
283                         TcpClient client = new TcpClient (clientSocket);
284                         
285                         return(client);
286                 }
287                 
288                 /// <summary>
289                 /// Tells the TcpListener to stop listening and dispose
290                 /// of all managed resources.
291                 /// </summary>
292                 public void Stop ()
293                 {
294                         if (active) 
295                         {
296                                 server.Close ();
297                                 server = null;
298                         }
299
300                         Init (AddressFamily.InterNetwork, savedEP);
301                 }
302
303                 public Task<Socket> AcceptSocketAsync ()
304                 {
305                         return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
306                 }
307
308                 public Task<TcpClient> AcceptTcpClientAsync ()
309                 {
310                         return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
311                 }
312         }
313 }