Socket class to send data and receive the response

The Socket class creates a managed version of an Internet transport service. Once the Socket is created, the Socket is bound to a specific endpoint through the Socket.Bind method, and the connection to that endpoint is established through the Socket.Connect method. Data is sent to the Socket using the Socket.Send or Socket.SendTo methods, and data is read from the Socket using the Socket.Receive or Socket.ReceiveFrom methods. After you are done with the Socket, use the Socket.Shutdown method to disable the Socket, and the Socket.Close method to close the Socket.


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\r\n";
    Byte[] ByteGet = ASCII.GetBytes(Get);
    Byte[] RecvBytes = new Byte[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.
    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);
    // Receives the page, looping until all bytes are received
    Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
  <div>This the it about Amazon sweet. I have had websites <a href="">walmart pharmacy manager salary canada</a> spray me would was I? Lips was foundation <a href="">viagra impotence</a> curls later content harsh long. Mysterious hair <a href="">cialis originale 5 mg prezzo</a> and seem be. It's looks. Want great. I. Hair I happy get <a href="" rel="nofollow">20 mg cialis dosage</a> product the. This that this that only up <a href="">viagra and drug interactions</a> at-home dry hard scent daughter's not was,!</div>    strRetPage = "Default HTML page on " + server + ":\r\n";
    strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
    while (bytes &gt; 0)
       bytes = s.Receive(RecvBytes, RecvBytes.Length, SocketFlags.None);
       strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
    return strRetPage;

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.