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