共用方式為


Socket Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Implements the Berkeley sockets interface.

Inheritance Hierarchy

System.Object
  System.Net.Sockets.Socket

Namespace:  System.Net.Sockets
Assembly:  System.Net (in System.Net.dll)

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Class Socket _
    Implements IDisposable
[SecuritySafeCriticalAttribute]
public class Socket : IDisposable

The Socket type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows Phone Socket Initializes a new instance of the Socket class using the specified address family, socket type and protocol.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows Phone AddressFamily Gets the address family of the Socket.
Public propertySupported by Silverlight for Windows Phone Connected Gets a value that indicates whether a Socket is connected to a remote host as of the last operation.
Public propertySupported by Silverlight for Windows Phone NoDelay Gets or sets a Boolean value that specifies whether the Socket is using the Nagle algorithm.
Public propertyStatic memberSupported by Silverlight for Windows Phone OSSupportsIPv4 Gets a value indicating whether IPv4 support is available and enabled on the current host.
Public propertyStatic memberSupported by Silverlight for Windows Phone OSSupportsIPv6 Gets a value indicating whether IPv6 support is available and enabled on the current host.
Public propertySupported by Silverlight for Windows Phone ProtocolType Gets the protocol type of the Socket.
Public propertySupported by Silverlight for Windows Phone ReceiveBufferSize Gets or sets a value that specifies the size of the receive buffer of the Socket.
Public propertySupported by Silverlight for Windows Phone RemoteEndPoint Gets the remote endpoint.
Public propertySupported by Silverlight for Windows Phone SendBufferSize Gets or sets a value that specifies the size of the send buffer of the Socket.
Public propertySupported by Silverlight for Windows Phone Ttl Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.

Top

Methods

  Name Description
Public methodStatic memberSupported by Silverlight for Windows Phone CancelConnectAsync Cancels an outstanding asynchronous socket operation for a remote host connection.
Public methodSupported by Silverlight for Windows Phone Close() Closes the Socket connection and releases all associated resources.
Public methodSupported by Silverlight for Windows Phone Close(Int32) Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.
Public methodSupported by Silverlight for Windows Phone ConnectAsync(SocketAsyncEventArgs) Begins an asynchronous request for a remote host connection.
Public methodStatic memberSupported by Silverlight for Windows Phone ConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs) Begins an asynchronous request for a remote host connection.
Public methodSupported by Silverlight for Windows Phone Dispose() Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Protected methodSupported by Silverlight for Windows Phone Dispose(Boolean) Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Public methodSupported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone Finalize Frees resources used by the Socket class. (Overrides Object.Finalize().)
Public methodSupported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone ReceiveAsync Begins an asynchronous request to receive data from a connected Socket object.
Public methodSupported by Silverlight for Windows Phone ReceiveFromAsync Begins an asynchronous request to receive data from a specific remote host.
Public methodSupported by Silverlight for Windows Phone SendAsync Sends data asynchronously to a connected Socket object.
Public methodSupported by Silverlight for Windows Phone SendToAsync Sends data asynchronously to a specific remote host.
Public methodSupported by Silverlight for Windows Phone Shutdown Disables sends and receives on a Socket.
Public methodSupported by Silverlight for Windows Phone ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

The Socket class provides a set of methods and properties for network communications. The Socket class allows you to perform asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.

For Silverlight for the desktop, the only supported ProtocolType is the TCP protocol. For Silverlight for the desktop, TCP unicast and UDP multicast clients are supported.

Silverlight for Windows Phone For Windows Phone OS 7.1, the supported ProtocolType values are the TCP and UDP protocol. For Windows Phone OS 7.1, TCP unicast, UDP unicast, and UDP multicast clients are supported.

When you are finished sending and receiving data, use the Shutdown method to disable the Socket. After calling Shutdown, call the Close method to release all resources associated with the Socket.

Normally, a client will initiate a connection to the host from which the web page with the XAML application was downloaded. One method that can be used to determine the host name from which the web page was downloaded is to use the System.Windows.Application class in the System.Windows namespace to get the Application.Current property of the Silverlight application. This property returns a System.Windows.Interop.SilverlightHost instance for the Silverlight application. The SilverlightHost.Source property on this instance gets the Uri used to connect to the host. The Uri.Host property gets the host component of this instance. This host component can then be used with a port number to construct a new DnsEndPoint instance by calling one of the DnsEndPoint constructors.

If the XAP file for the XAML application was loaded using a Uri of Uri.UriSchemeFile to a file on the local computer, the SilverlightHost.Source property is set to a Uri with the Uri.Scheme property set to Uri.UriSchemeFile and the Uri.Host property will not be valid for use in a System.Net.DnsEndPoint.

If the XAP file for the XAML application was loaded using a Uri of Uri.UriSchemeHttp to a web page on the local computer, the SilverlightHost.Source property is set to a Uri with the Uri.Scheme property set to Uri.UriSchemeHttp and the Uri.Host property is set to localhost.

For sockets, the security policy system in Silverlight 2 and later affects both site-of-origin and cross-domain network access. A security policy is required for any connections from sockets, even when the connection is back to the site of origin. For more information on the security policy system in Silverlight, see Network Security Access Restrictions in Silverlight.

Examples

  public class Example
  {
    static ManualResetEvent clientDone = new ManualResetEvent(false);

    public static void Demo(System.Windows.Controls.TextBlock outputBlock)
    {

        SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            DnsEndPoint hostEntry = new DnsEndPoint("https://www.contoso.com", 80);

        // Create a socket and connect to the server
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed);

        socketEventArg.RemoteEndPoint = hostEntry;
        socketEventArg.UserToken = sock;
        sock.ConnectAsync(socketEventArg);
        clientDone.WaitOne();
    }

    // A single callback is used for all socket operations. 
    // This method forwards execution on to the correct handler 
    // based on the type of completed operation
    static void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e)
    {
        switch (e.LastOperation)
        {
            case SocketAsyncOperation.Connect:
                ProcessConnect(e);
                break;
            case SocketAsyncOperation.Receive:
                ProcessReceive(e);
                break;
            case SocketAsyncOperation.Send:
                ProcessSend(e);
                break;
            default:
                throw new Exception("Invalid operation completed");
        }
    }

    // Called when a ConnectAsync operation completes
    private static void ProcessConnect(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            // Successfully connected to the server

            // Send 'Hello World' to the server
            byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
            e.SetBuffer(buffer, 0, buffer.Length);
            Socket sock = e.UserToken as Socket;
            bool willRaiseEvent = sock.SendAsync(e);
            if (!willRaiseEvent)
            {
                ProcessSend(e);
            }
        }
        else
        {
            throw new SocketException((int)e.SocketError);
        }
    }

        // Called when a ReceiveAsync operation completes
        // </summary>
    private static void ProcessReceive(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            // Received data from server

        // Data has now been sent and received from the server. 
        // Disconnect from the server
            Socket sock = e.UserToken as Socket;
            sock.Shutdown(SocketShutdown.Send);
            sock.Close();
            clientDone.Set();
        }
        else
        {
            throw new SocketException((int)e.SocketError);
        }
    }


    // Called when a SendAsync operation completes
    private static void ProcessSend(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            // Sent "Hello World" to the server successfully

            //Read data sent from the server
            Socket sock = e.UserToken as Socket;
            bool willRaiseEvent = sock.ReceiveAsync(e);
            if (!willRaiseEvent)
            {
                ProcessReceive(e);
            }
        }
        else
        {
            throw new SocketException((int)e.SocketError);
        }
    }
  }

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference