Socket Class
Assembly: System (in system.dll)
The Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration. The Socket class follows the .NET Framework naming pattern for asynchronous methods; for example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.
If your application only requires one thread during execution, use the following methods, which are designed for synchronous operation mode.
-
If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. Use this returned Socket to call the Send or Receive method. Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the Connect method. To communicate data, call the Send or Receive method.
-
If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the ReceiveFrom method to accept any incoming datagrams. Use the SendTo method to send datagrams to a remote host.
To process communications using separate threads during execution, use the following methods, which are designed for asynchronous operation mode.
-
If you are using a connection-oriented protocol such as TCP, use the Socket, BeginConnect, and EndConnect methods to connect with a listening host. Use the BeginSend and EndSend or BeginReceive and EndReceive methods to communicate data asynchronously. Incoming connection requests can be processed using BeginAccept and EndAccept.
-
If you are using a connectionless protocol such as UDP, you can use BeginSendTo and EndSendTo to send datagrams, and BeginReceiveFrom and EndReceiveFrom to receive datagrams.
If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.
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.
The Socket class allows you to configure your Socket using the SetSocketOption method. Retrieve these settings using the GetSocketOption method.
Note |
|---|
| If you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications. |
Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: Not all socket options are supported on all device operating systems.
The following code example shows how the Socket class can be used to send data to an HTTP server and receive the response. This example blocks until the entire page is received.
Imports System Imports System.Text Imports System.IO Imports System.Net Imports System.Net.Sockets Imports Microsoft.VisualBasic Public Class GetSocket Private Shared Function ConnectSocket(server As String, port As Integer) As Socket Dim s As Socket = Nothing Dim hostEntry As IPHostEntry = Nothing ' Get host related information. hostEntry = Dns.GetHostEntry(server) ' Loop through the AddressList to obtain the supported AddressFamily. This is to avoid ' an exception that occurs when the host host IP Address is not compatible with the address family ' (typical in the IPv6 case). Dim address As IPAddress For Each address In hostEntry.AddressList Dim endPoint As New IPEndPoint(address, port) Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) tempSocket.Connect(endPoint) If tempSocket.Connected Then s = tempSocket Exit For End If Next address Return s End Function ' This method requests the home page content for the specified server. Private Shared Function SocketSendReceive(server As String, port As Integer) As String 'Set up variables and String to write to the server. Dim ascii As Encoding = Encoding.ASCII Dim request As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf Dim bytesSent As [Byte]() = ascii.GetBytes(request) Dim bytesReceived(255) As [Byte] ' Create a socket connection with the specified server and port. Dim s As Socket = ConnectSocket(server, port) If s Is Nothing Then Return "Connection failed" End If ' Send request to the server. s.Send(bytesSent, bytesSent.Length, 0) ' Receive the server home page content. Dim bytes As Int32 ' Read the first 256 bytes. Dim page as [String] = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf ' The following will block until the page is transmitted. Do bytes = s.Receive(bytesReceived, bytesReceived.Length, 0) page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes) Loop While bytes > 0 Return page End Function 'Entry point which delegates to C-style main Private Function Public Overloads Shared Sub Main() Main(System.Environment.GetCommandLineArgs()) End Sub Overloads Private Shared Sub Main(args() As String) Dim host As String Dim port As Integer = 80 If args.Length = 1 Then ' If no server name is passed as argument to this program, ' use the current host name as default. host = Dns.GetHostName() Else host = args(1) End If Dim result As String = SocketSendReceive(host, port) Console.WriteLine(result) End Sub 'Main End Class
import System.*;
import System.Text.*;
import System.IO.*;
import System.Net.*;
import System.Net.Sockets.*;
public class GetSocket
{
private static Socket ConnectSocket(String server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.Resolve(server);
// Loop through the AddressList to obtain the supported AddressFamily.
// This is to avoid an exception that occurs when the host IP Address
// is not compatible with the address family
// (typical in the IPv6 case).
for (int iCtr = 0; iCtr < hostEntry.get_AddressList().length; iCtr++) {
IPAddress address = hostEntry.get_AddressList()[iCtr];
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket = new Socket(ipe.get_AddressFamily(),
SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.get_Connected()) {
s = tempSocket;
break;
}
else {
continue;
}
}
return s;
} //ConnectSocket
// This method requests the home page content for the specified server.
private static String SocketSendReceive(String server, int port)
{
String request = "GET / HTTP/1.1\r\nHost: " + server
+ "\r\nConnection: Close\r\n\r\n";
System.Byte bytesSent[] =
(System.Byte[])Encoding.get_ASCII().GetBytes(request);
System.Byte bytesReceived[] = new System.Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(server, port);
if (s == null) {
return "Connection failed";
}
// Send request to the server.
s.Send((ubyte[])bytesSent, bytesSent.length, (SocketFlags)0);
// Receive the server home page content.
int bytes = 0;
String page = "Default HTML page on " + server + ":\r\n";
// The following will block until te page is transmitted.
do {
bytes = s.Receive((ubyte[])bytesReceived,
bytesReceived.length, (SocketFlags)0);
page = page + Encoding.get_ASCII().GetString(
(ubyte[])bytesReceived, 0, bytes);
} while (bytes > 0);
return page;
} //SocketSendReceive
public static void main(String[] args)
{
String host;
int port = 80;
if (args.length == 0) {
// If no server name is passed as argument to this program,
// use the current host name as the default.
host = Dns.GetHostName();
}
else {
host = args[0];
}
String result = SocketSendReceive(host, port);
Console.WriteLine(result);
} //main
} //GetSocket
- SocketPermission To establish an outgoing connection or accept an incoming request.
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
Note