Use C # To develop Socket communication

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.