The simple socket implementation of the HTTP Server

Source: Internet
Author: User
Tags rfc

Code Http://note.youdao.com/share/?id=1d28ee946720332255efc72c3e12a0da&type=note

Reference http://blog.csdn.net/u010687392/article/details/44649589

/** * * @className: Mainactivity * @description: Mobile Infrared Client: Processing infrared code for TV request transmission * @author: Administrator * @date: September 6, 2015 9:40:    */public class Mainactivity extends activity{private TextView minputtext;    ServerSocket server = null;    Socket socket = NULL;        Private TextView Mtitletext;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mtitletext = (TextView) Findviewbyid (r.id.title);        Minputtext = (TextView) Findviewbyid (r.id.msg);        Initservicedata ();            Mtitletext.settext ("IP:" + getip ());        } private String GetIP () {Wifimanager Wifimanger = (wifimanager) getsystemservice (Wifi_service);        Wifiinfo wifiinfo = Wifimanger.getconnectioninfo ();        int i = wifiinfo.getipaddress (); Return (I & 0xFF) + "." + (((I >> 8) & 0xFF) + "." + ((I >> +) & 0xFF) + "." + (I >> &amp ;    0xFF); }        private void Initservicedata () {new Thread () {@Override public void Run () {try {server = new ServerSocket (8888);//Create a serversocket and let Socke                    T listen on port 8888//Call ServerSocket's Accept () method, accept the request sent by the client, and create a socket object                        If the client does not send the data, then the thread will stall without continuing, that is, blocking while (true) {socket = server.accept (); System.out.println ("Host:" + socket.getinetaddress (). GetHostName () + ", IP:" + socket.getinetaddress (). g                        Ethostaddress ());//Gets the host name and IP address of the current send data socket object//Read client message                        InputStream InputStream = Socket.getinputstream ();                        Bufferedinputstream bis = new Bufferedinputstream (InputStream);                        Byte[] B = new byte[inputstream.available ()];   Byte[] B = new byte[1024 * 2];                     int len =-1;                        Final StringBuilder StringBuilder = new StringBuilder ();                            while (len = Bis.read (b))! =-1) {String msg = new String (b, 0, Len, "UTF-8");                            SYSTEM.OUT.PRINTLN (msg);                            Stringbuilder.append (msg); break;//can only read 2048 of its own request data at a time, of course, more content lenght compute, and then jump out of the loop.                                                Note. Here read (b) will never be-1 because the socket will attempt to read the client's data after reading to the end of the input stream}                            Runonuithread (New Runnable () {@Override                                public void Run () {Httprequestparser httprequestparser = new Httprequestparser (); try {httprequestparser.parserequest (Stringbuilder.tostrin                                    g ()); Minputtext.append (StringBuilder.ToString () + "\n=================\n\n");                                    Minputtext.append (Urldecoder.decode (Httprequestparser.getmessagebody (), "UTF-8"));                                                                    LOG.D ("TAG", "params is" + Urldecoder.decode (Httprequestparser.getmessagebody (), "UTF-8"));                                    } catch (IOException e) {                                E.printstacktrace ();                                } catch (Httpformatexception e) {e.printstacktrace ();                        }                                                            }                        }); Socket.shutdowninput ();//end read//--------return information to the client----                        ---------OutputStream Outputresult = Socket.getoutputstream (); StringBuffer sb = new STRIngbuffer ();                        Sb.append ("http/1.1 ok\r\n");                        Sb.append ("Host:" + socket.getinetaddress (). GetHostName () + "\ r \ n");                        Sb.append ("\ r \ n");                        Outputresult.write (Sb.tostring (). GetBytes ());                        Outputresult.write ("ok,received". GetBytes ());                                                Outputresult.flush (); Bis.close ();//close the cache input stream, note that the input stream inputs do not need to be closed because it only gets the input stream object in the socket and is not created socket.cl OSE ();//The resource is freed after receiving the data from this socket, because every time the client sends the data it creates a socket object on the server, noting that ServerSocket should not be shut down, because this is the ServerSocket object,                                            The client cannot send data without the socket = NULL;                }} catch (IOException e) {e.printstacktrace ();            }}}.start (); }}



HTTP message parsing class
/** * Class for HTTP request parsing as defined by RFC 2612: * * request = Request-line; Section 5.1 (General-header; Section 4.5 | * Request-header; Section 5.3 | Entity-header) CRLF); Section 7.1 CRLF [* message-body];    Section 4.3 * * @author Izelaya * */public class httprequestparser{private String _requestline;    Private hashmap<string, string> _requestheaders;        Private StringBuffer _messagetbody;        Public Httprequestparser () {_requestheaders = new hashmap<string, string> ();    _messagetbody = new StringBuffer ();     }/** * Parse and HTTP request.     * * @param request * String holding HTTP request.     * @throws IOException * If an I/O error occurs reading the input stream. * @throws httpformatexception * If HTTP Request is malformed */public void Parserequest (String req uest) throws IOException, httpformatexception {if (Textutils.isempty (Request)) {return;                } BufferedReader reader = new BufferedReader (new StringReader (request)); Setrequestline (Reader.readline ()); Request-line;        Section 5.1 String Header = Reader.readline ();            while (Header.length () > 0) {appendheaderparameter (header);        Header = Reader.readline ();        } String Bodyline = Reader.readline ();            while (Bodyline! = null) {appendmessagebody (Bodyline);        Bodyline = Reader.readline ();  }}/** * * 5.1 request-line The Request-line begins with a method token, followed by * the Request-uri and the protocol version, and ending with CRLF. The * elements is separated by SP characters.     No CR or LF is allowed except in * The final CRLF sequence.    * * @return string with Request-line */public string getrequestline () {return _requestline; } private void Setrequestline (StRing Requestline) throws Httpformatexception {if (Requestline = = NULL | | requestline.length () = = 0) {T        Hrow New Httpformatexception ("Invalid request-line:" + requestline);    } _requestline = Requestline; The private void Appendheaderparameter (String header) throws httpformatexception {int idx = Header.indexof (":        ");        if (idx = =-1) {throw new Httpformatexception ("Invalid header Parameter:" + header);    } _requestheaders.put (header.substring (0, IDX), header.substring (idx + 1, header.length ()));  }/** * The Message-body (if any) of a HTTP message is used to carry, the * Entity-body associated with the Request or response. The message-body * differs from the entity-body if a transfer-coding have been * applied, as indicated by th     E transfer-encoding Header Field (section * 14.41). * * @return string with Message-body */public string getmessagebody () {RETurn _messagetbody.tostring ();    private void Appendmessagebody (String bodyline) {_messagetbody.append (Bodyline). Append ("\ r \ n"); }/** * For List of available headers refer to sections:4.5, 5.3, 7.1 of RFC * 2616 * * @param he     Adername * Name of header * @return String with the value of the header or null if not found.    */public string Getheaderparam (string headername) {return _requestheaders.get (headername);  } public class Httpformatexception extends Exception {private static final long Serialversionuid                = 1L; Public httpformatexception (String string) {}}}



The simple socket implementation of the HTTP Server

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.