The simplest HTTP server Java version

xiaoxiao2021-03-06  123

Only single threads are supported, only one request can be received

I want to improve, let it receive multiple requests

Note I will not add it.

You can refer to the Winsock version, as if Java is simpler

?

Import java.io. *; import java.ut. *; import java.util. *;

? Public class WebServer {public static void main (String [] args) throws Exception {??? String requestMessageLine; ??? String fileName; ??? ServerSocket listenSocket = new ServerSocket (80); ??? Socket connectSocket = listenSocket. accept (); ??? BufferedReader inFormClient = new BufferedReader (new ??????? InputStreamReader (connectSocket.getInputStream ())); ??? DataOutputStream outToClient = new ??????? DataOutputStream (connectSocket.getOutputStream ()); ??? requestMessageLine = inFormClient.readLine (); ??? StringTokenizer tokenizedLine = new StringTokenizer (requestMessageLine); ??? if (tokenizedLine.nextToken (). equals ( "GET")) {???? Filename = tokenizedLine.nextToken (); ????? if (filename.startswith ("/") == true) {??????? filename = filename.substring (1); ?????? } ????? string filepath = new string ("d: // java // httpserver // classes //"); ????? file file = new file (filepath filename); ????? NumofBytes = (int) file.Length (); ????? fileinputstream infile = new fileinputstream (filepath filename); ????? byte [] fileinbytes = new byte [numofbytes];? ????? INFILE.READ (FileinBytes); ????? Outtoclient.writebytes ("http / 1.0 200 document follows / r / n"); ????? ing (filename.endswith (". jpg") ) {???????? OUTTOCLIENT.WRITEBYTES ("Conten-Type: Image / JPEG / R / N"); ?????} ????? Else IF (FileName.endSwith (". GIF ")) {???????? OUTTOCLIENT.WRITEBYTES (" Conten-type: image / gif / r / n "); ?????} ????? Outtoclient.writeBytes (" Content-Length : " Numofbytes " / r / n "); ????? Outtoclient.writebytes (" / r / n "); ????? Outtoclient.write (fileinbytes, 0, numofbytes); ???? ? ConnectSocket.close ();

???} ??? Else {????? system.out.println ("No support for other request except get!"); ???}?}}

转载请注明原文地址:https://www.9cbs.com/read-126758.html

New Post(0)