The following example shows how to use the Socket class to send data to the HTTP server and receive responses.
[C #]
Public string DoSocketGet (string server)
{
// Sets up variables and a string to write to the server
Encoding ASCII = Encoding. ASCII;
String Get = "GET/HTTP/1.1 \ r \ nHost:" + server +
"\ R \ nConnection: Close \ r \ n ";
Byte [] ByteGet = ASCII. GetBytes (Get );
Byte [] RecvBytes = new Byte [1, 256];
String strRetPage = null;
// IPAddress and IPEndPoint represent the endpoint that will
// Receive the request.
// Get the first IPAddress in the list using DNS.
IPAddress hostadd = Dns. Resolve (server). AddressList [0];
IPEndPoint EPhost = new IPEndPoint (hostadd, 80 );
// Creates the Socket for sending data over TCP.
Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream,
ProtocolType. Tcp );
// Connects to the host using IPEndPoint.
S. Connect (EPhost );
If (! S. Connected)
{
StrRetPage = "Unable to connect to host ";
Return strRetPage;
}
// Sends the GET text to the host.
S. Send (ByteGet, ByteGet. Length, SocketFlags. None );
// Perform es the page, looping until all bytes are stored ed
Int32 bytes = s. Receive (RecvBytes, RecvBytes. Length, 0 );
StrRetPage = "Default HTML page on" + server + ": \ r \ n ";
StrRetPage = strRetPage + ASCII. GetString (RecvBytes, 0, bytes );
While (bytes> 0)
{
Bytes = s. Receive (RecvBytes, RecvBytes. Length, SocketFlags. None );
StrRetPage = strRetPage + ASCII. GetString (RecvBytes, 0, bytes );
}
// If You Want To immediately Close the connection, call s. Close ();
Return strRetPage;
}