Code:
/ Dotnetfx_Vista_SP2 / Dotnetfx_Vista_SP2 / 8.0.50727.4016 / DEVDIV / depot / DevDiv / releases / whidbey / NetFxQFE / ndp / fx / src / Net / System / Net / Sockets / TCPListener.cs / 1 / TCPListener.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Net.Sockets {
using System;
using System.Net;
using System.Security.Permissions;
///
/// The class provide TCP services at a higher level of abstraction than the
/// class. is used to create a host process that
/// listens for connections from TCP clients.
///
public class TcpListener {
IPEndPoint m_ServerSocketEP;
Socket m_ServerSocket;
bool m_Active;
bool m_ExclusiveAddressUse;
///
///
/// Initializes a new instance of the TcpListener class with the specified local
/// end point.
///
///
public TcpListener(IPEndPoint localEP) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localEP);
if (localEP == null) {
throw new ArgumentNullException("localEP");
}
m_ServerSocketEP = localEP;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
///
///
/// Initializes a new instance of the TcpListener class that listens to the
/// specified IP address and port.
///
///
public TcpListener(IPAddress localaddr, int port) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localaddr);
if (localaddr == null) {
throw new ArgumentNullException("localaddr");
}
if (!ValidationHelper.ValidateTcpPort(port)) {
throw new ArgumentOutOfRangeException("port");
}
m_ServerSocketEP = new IPEndPoint(localaddr, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
// implementation picks an address for client
///
///
/// Initiailizes a new instance of the TcpListener class
/// that listens on the specified
/// port.
///
///
///
[Obsolete("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListener(int port){
if (!ValidationHelper.ValidateTcpPort(port))
throw new ArgumentOutOfRangeException("port");
m_ServerSocketEP = new IPEndPoint(IPAddress.Any, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
///
///
/// Used by the class to provide the underlying network socket.
///
///
public Socket Server {
get {
return m_ServerSocket;
}
}
///
///
/// Used
/// by the class to indicate that the listener's socket has been bound to a port
/// and started listening.
///
///
protected bool Active {
get {
return m_Active;
}
}
///
///
/// Gets the m_Active EndPoint for the local listener socket.
///
///
public EndPoint LocalEndpoint {
get {
return m_Active ? m_ServerSocket.LocalEndPoint : m_ServerSocketEP;
}
}
public bool ExclusiveAddressUse {
get {
return m_ServerSocket.ExclusiveAddressUse;
}
set{
if (m_Active) {
throw new InvalidOperationException(SR.GetString(SR.net_tcplistener_mustbestopped));
}
m_ServerSocket.ExclusiveAddressUse = value;
m_ExclusiveAddressUse = value;
}
}
// Start/stop the listener
///
///
/// Starts listening to network requests.
///
///
public void Start() {
Start((int)SocketOptionName.MaxConnections);
}
public void Start(int backlog) {
if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0) {
throw new ArgumentOutOfRangeException("backlog");
}
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Start", null);
GlobalLog.Print("TCPListener::Start()");
if (m_ServerSocket == null)
throw new InvalidOperationException(SR.GetString(SR.net_InvalidSocketHandle));
//already listening
if (m_Active) {
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
return;
}
m_ServerSocket.Bind(m_ServerSocketEP);
m_ServerSocket.Listen(backlog);
m_Active = true;
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
}
///
///
/// Closes the network connection.
///
///
public void Stop() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Stop", null);
GlobalLog.Print("TCPListener::Stop()");
if (m_ServerSocket != null) {
m_ServerSocket.Close();
m_ServerSocket = null;
}
m_Active = false;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (m_ExclusiveAddressUse) {
m_ServerSocket.ExclusiveAddressUse = true;
}
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Stop", null);
}
// Determine if there are pending connections
///
///
/// Determine if there are pending connection requests.
///
///
public bool Pending() {
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
return m_ServerSocket.Poll(0, SelectMode.SelectRead);
}
// Accept the first pending connection
///
///
/// Accepts a pending connection request.
///
///
public Socket AcceptSocket() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket socket = m_ServerSocket.Accept();
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptSocket", socket);
return socket;
}
// UEUE
///
/// [To be supplied.]
///
public TcpClient AcceptTcpClient() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket acceptedSocket = m_ServerSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptTcpClient", returnValue);
return returnValue;
}
//methods
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptSocket", null);
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptSocket", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptSocket", socket);
return socket;
}
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptTcpClient", null);
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptTcpClient", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptTcpClient", socket);
return new TcpClient(socket);
}
}; // class TcpListener
} // namespace System.Net.Sockets
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Net.Sockets {
using System;
using System.Net;
using System.Security.Permissions;
///
/// The class provide TCP services at a higher level of abstraction than the
/// class. is used to create a host process that
/// listens for connections from TCP clients.
///
public class TcpListener {
IPEndPoint m_ServerSocketEP;
Socket m_ServerSocket;
bool m_Active;
bool m_ExclusiveAddressUse;
///
///
/// Initializes a new instance of the TcpListener class with the specified local
/// end point.
///
///
public TcpListener(IPEndPoint localEP) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localEP);
if (localEP == null) {
throw new ArgumentNullException("localEP");
}
m_ServerSocketEP = localEP;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
///
///
/// Initializes a new instance of the TcpListener class that listens to the
/// specified IP address and port.
///
///
public TcpListener(IPAddress localaddr, int port) {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "TcpListener", localaddr);
if (localaddr == null) {
throw new ArgumentNullException("localaddr");
}
if (!ValidationHelper.ValidateTcpPort(port)) {
throw new ArgumentOutOfRangeException("port");
}
m_ServerSocketEP = new IPEndPoint(localaddr, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "TcpListener", null);
}
// implementation picks an address for client
///
///
/// Initiailizes a new instance of the TcpListener class
/// that listens on the specified
/// port.
///
///
///
[Obsolete("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListener(int port){
if (!ValidationHelper.ValidateTcpPort(port))
throw new ArgumentOutOfRangeException("port");
m_ServerSocketEP = new IPEndPoint(IPAddress.Any, port);
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
///
///
/// Used by the class to provide the underlying network socket.
///
///
public Socket Server {
get {
return m_ServerSocket;
}
}
///
///
/// Used
/// by the class to indicate that the listener's socket has been bound to a port
/// and started listening.
///
///
protected bool Active {
get {
return m_Active;
}
}
///
///
/// Gets the m_Active EndPoint for the local listener socket.
///
///
public EndPoint LocalEndpoint {
get {
return m_Active ? m_ServerSocket.LocalEndPoint : m_ServerSocketEP;
}
}
public bool ExclusiveAddressUse {
get {
return m_ServerSocket.ExclusiveAddressUse;
}
set{
if (m_Active) {
throw new InvalidOperationException(SR.GetString(SR.net_tcplistener_mustbestopped));
}
m_ServerSocket.ExclusiveAddressUse = value;
m_ExclusiveAddressUse = value;
}
}
// Start/stop the listener
///
///
/// Starts listening to network requests.
///
///
public void Start() {
Start((int)SocketOptionName.MaxConnections);
}
public void Start(int backlog) {
if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0) {
throw new ArgumentOutOfRangeException("backlog");
}
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Start", null);
GlobalLog.Print("TCPListener::Start()");
if (m_ServerSocket == null)
throw new InvalidOperationException(SR.GetString(SR.net_InvalidSocketHandle));
//already listening
if (m_Active) {
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
return;
}
m_ServerSocket.Bind(m_ServerSocketEP);
m_ServerSocket.Listen(backlog);
m_Active = true;
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Start", null);
}
///
///
/// Closes the network connection.
///
///
public void Stop() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "Stop", null);
GlobalLog.Print("TCPListener::Stop()");
if (m_ServerSocket != null) {
m_ServerSocket.Close();
m_ServerSocket = null;
}
m_Active = false;
m_ServerSocket = new Socket(m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (m_ExclusiveAddressUse) {
m_ServerSocket.ExclusiveAddressUse = true;
}
if(Logging.On)Logging.Exit(Logging.Sockets, this, "Stop", null);
}
// Determine if there are pending connections
///
///
/// Determine if there are pending connection requests.
///
///
public bool Pending() {
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
return m_ServerSocket.Poll(0, SelectMode.SelectRead);
}
// Accept the first pending connection
///
///
/// Accepts a pending connection request.
///
///
public Socket AcceptSocket() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket socket = m_ServerSocket.Accept();
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptSocket", socket);
return socket;
}
// UEUE
///
/// [To be supplied.]
///
public TcpClient AcceptTcpClient() {
if(Logging.On)Logging.Enter(Logging.Sockets, this, "AcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
Socket acceptedSocket = m_ServerSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "AcceptTcpClient", returnValue);
return returnValue;
}
//methods
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptSocket", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptSocket", null);
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptSocket", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptSocket", socket);
return socket;
}
[HostProtection(ExternalThreading=true)]
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, this, "BeginAcceptTcpClient", null);
if (!m_Active)
throw new InvalidOperationException(SR.GetString(SR.net_stopped));
IAsyncResult result = m_ServerSocket.BeginAccept(callback,state);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "BeginAcceptTcpClient", null);
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult){
if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndAcceptTcpClient", null);
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndAcceptTcpClient", socket);
return new TcpClient(socket);
}
}; // class TcpListener
} // namespace System.Net.Sockets
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- ILGen.cs
- SimpleHandlerFactory.cs
- ListDictionaryInternal.cs
- PinnedBufferMemoryStream.cs
- SHA384.cs
- HiddenField.cs
- PkcsUtils.cs
- QilInvokeLateBound.cs
- WebBaseEventKeyComparer.cs
- WsdlBuildProvider.cs
- PropertyCollection.cs
- ReliableOutputSessionChannel.cs
- BypassElementCollection.cs
- NavigateEvent.cs
- selecteditemcollection.cs
- KnownColorTable.cs
- ServiceDesigner.xaml.cs
- SpotLight.cs
- CodeNamespaceImport.cs
- KeyboardInputProviderAcquireFocusEventArgs.cs
- ImageButton.cs
- EncoderParameter.cs
- BridgeDataRecord.cs
- WrapPanel.cs
- PropertyPath.cs
- GlyphInfoList.cs
- DataListAutoFormat.cs
- SiblingIterators.cs
- PointConverter.cs
- DataSpaceManager.cs
- StrongNameUtility.cs
- BidOverLoads.cs
- DataObjectAttribute.cs
- ImpersonationContext.cs
- X509CertificateEndpointIdentity.cs
- SecurityMessageProperty.cs
- XmlNamespaceMappingCollection.cs
- SessionStateUtil.cs
- ProfileInfo.cs
- COM2Properties.cs
- BackStopAuthenticationModule.cs
- InitializationEventAttribute.cs
- _LazyAsyncResult.cs
- EmptyElement.cs
- StringInfo.cs
- Image.cs
- bidPrivateBase.cs
- Attributes.cs
- ContextCorrelationInitializer.cs
- SimpleBitVector32.cs
- DynamicActivity.cs
- DataGridHeaderBorder.cs
- SchemaNamespaceManager.cs
- PrimaryKeyTypeConverter.cs
- ArgumentNullException.cs
- HostedHttpTransportManager.cs
- AmbientProperties.cs
- IdleTimeoutMonitor.cs
- CryptoProvider.cs
- InvokeSchedule.cs
- ProtocolViolationException.cs
- TempFiles.cs
- BuildResultCache.cs
- InkSerializer.cs
- ComboBoxRenderer.cs
- DesignSurface.cs
- HttpCapabilitiesEvaluator.cs
- DiagnosticTrace.cs
- EdmFunctionAttribute.cs
- SparseMemoryStream.cs
- CqlParserHelpers.cs
- Brush.cs
- BooleanAnimationUsingKeyFrames.cs
- XmlLanguage.cs
- ReadOnlyHierarchicalDataSourceView.cs
- SQLInt64Storage.cs
- UIHelper.cs
- GatewayIPAddressInformationCollection.cs
- EventlogProvider.cs
- WindowsStatic.cs
- CommonObjectSecurity.cs
- SymbolMethod.cs
- DesignerAdapterUtil.cs
- InternalTypeHelper.cs
- Trace.cs
- WebContext.cs
- EnvelopeVersion.cs
- XmlEncoding.cs
- TrackingProfile.cs
- UseManagedPresentationElement.cs
- LinkClickEvent.cs
- IgnoreFileBuildProvider.cs
- PrimitiveType.cs
- LoginAutoFormat.cs
- StateItem.cs
- ConfigurationCollectionAttribute.cs
- cookiecontainer.cs
- XmlSchemaExternal.cs
- SqlMethodAttribute.cs
- XmlDeclaration.cs