C # socket parsing http protocol

Source: Internet
Author: User

C # simulate the HTTP protocol through socket and parse the HTTP Header

Find a good article and apply it to the MMS MM7 Protocol I am developing.
C # C #

** // <Summary>
/// Method for receiving data
/// </Summary>
/// <Param name = "socket"> Socket connection </param>
/// <Param name = "size"> length of data to be received </param>
/// <Returns> returns the received byte array </returns>
Public static byte [] ReceiveData (Socket socket, int size)
{
Int total = 0; // The total number of bytes received
Int dataleft = size; // remaining bytes
Byte [] data = new byte [size]; // array of received data
Int rece = 0; // number of received bytes
// Receive data cyclically
While (total <size)
{
Rece = socket. Receive (data, total, dataleft, socketflags. None );
// If the number of bytes received is 0, the connection is disconnected and an empty byte array is returned.
If (RECE = 0)
{
Break;
}
Total + = rece; // length of the received bytes + +
Dataleft-= rece; // remaining bytes --

}
Return data; // return
}
C # c #
Method overload

Public static byte [] ReceiveData (Socket socket)
{


StringBuilder header = new StringBuilder ();
String headertext = "";
While (true)
{
Byte [] data = new byte [1];
// Receives one byte
Int rece = socket. Receive (data, 1, SocketFlags. None );


// Convert to char
Char c = (char) data [0];

Header. Append (c );
// Check whether it is at the end of the packet header. If it is at the end of the packet header, it is stopped.
// Read
If (header. ToString (). IndexOf ("\ r \ n")> 0)
{
String content = "CONTENT-LENGTH :";
Int start = header. ToString (). ToUpper (). IndexOf (content );
Headertext = header. ToString (). Substring (start + content. Length );
Int end = headertext. IndexOf ("\ r \ n ");
Headertext = headertext. Substring (0, end); // package Length
Break;
}
}
//
Byte [] ds = ReceiveData (socket, Convert. ToInt16 (headertext ));
Return ds;
}

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.