Socket.Connect Method
public void Connect(EndPoint remoteEP);
public void Connect(string host, int port);
public bool Connect(string host, int port, bool ipv6Host);
public IAsyncResult Connect(EndPoint remoteEP, AsyncCallback callback, object state);
public IAsyncResult Connect(string host, int port, AsyncCallback callback, object state);
Description
Establishes a connection to a remote host. This method can be used to connect to a TCP server or to establish a connection to a UDP host.
When you use the Connect method with a connection-oriented protocol like TCP, the Connect method attempts to establish a connection to the remote host. If the connection is successful, your Socket object is ready for sending and receiving data.
If you are using a connectionless protocol like UDP, the Connect method establishes a default remote host to send datagrams to and receive datagrams from. Subsequent calls to Send will send data to that default address, and calls to Receive will receive data only from that default address. You do not need to specify the remoteEP or host and port in subsequent send and receive operations.
Parameters
| Name | Type | Description |
|---|---|---|
remoteEP |
System.Net.EndPoint |
An EndPoint that represents the remote device. |
host |
string |
The host name or IP address of the remote host. |
port |
int |
The port number of the remote host. |
ipv6Host |
bool |
A Boolean value that specifies whether the |
callback |
System.Net.Sockets.AsyncCallback |
An AsyncCallback delegate that references the method to call when the operation is complete. |
state |
object |
A user-defined object that contains context information for the asynchronous operation. |
Returns
For the synchronous overloads, this method returns void if successful. For the asynchronous overloads, it returns an IAsyncResult instance that references the asynchronous operation.
Exceptions
System.ArgumentException: The IP address family specified in the remote endpoint is not supported.System.Net.Sockets.SocketException: An error occurred while attempting to access the socket.System.ObjectDisposedException: TheSockethas been closed.System.InvalidOperationException: TheSocketis not bound to an address.
Remarks
You must call Connect to establish a connection before you can send and receive data using a connection-oriented protocol like TCP.
If you are using a connectionless protocol, such as UDP, the Connect method establishes a default remote host and port. This is useful for reducing the overhead of sending and receiving data to the same remote host repeatedly.
To use the Connect method with an EndPoint, you must first create an EndPoint object that specifies the remote host and port. For example, you can use an IPEndPoint object for TCP/IP connections.
The asynchronous version of the Connect method allows your application to continue executing while the connection is being established. You can then process the connection when the Connect operation completes by checking the IAsyncResult object returned by the method.
Example
The following example demonstrates how to use the Connect method to establish a TCP connection to a remote host.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketConnectExample
{
public static void Main(string[] args)
{
try
{
// Define the remote server IP address and port
string serverIp = "127.0.0.1"; // Replace with your server's IP address
int serverPort = 11000; // Replace with your server's port
// Create a TCP/IP socket.
using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
// Create an IPEndPoint object
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
Console.WriteLine($"Attempting to connect to {remoteEndPoint.Address}:{remoteEndPoint.Port}...");
// Connect to the remote endpoint.
clientSocket.Connect(remoteEndPoint);
Console.WriteLine("Connection established successfully!");
// Now you can send and receive data using clientSocket
string messageToSend = "Hello from client!";
byte[] messageBytes = Encoding.ASCII.GetBytes(messageToSend);
// Send data
int bytesSent = clientSocket.Send(messageBytes);
Console.WriteLine($"Sent {bytesSent} bytes: {messageToSend}");
// Example: Receive a response (assuming the server sends one)
byte[] buffer = new byte[1024];
int bytesReceived = clientSocket.Receive(buffer);
string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine($"Received {bytesReceived} bytes: {receivedMessage}");
// Close the socket
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (SocketException socketEx)
{
Console.WriteLine($"SocketException: {socketEx.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}