tiny java_tiny java web server

司寇羽
2023-12-01

import java.io.*;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;/*** Created by Administrator on 2016/7/29.*/

public class HttpDemo extendsThread

{privateServerSocket serverSocket;private int port = 80;public voidrun()

{

String[] MIME_TYPES={"text/html","image/jpeg","image/png","image/gif","application/javascript","text/css",

};try{

serverSocket= newServerSocket(port);while(true) {

Socket connectedClient=serverSocket.accept();

DataInputStream inStream= newDataInputStream(connectedClient.getInputStream());

BufferedReader bufferedReader= new BufferedReader(newInputStreamReader(inStream));

String str=bufferedReader.readLine();

ArrayList headers = newArrayList();

String encoding= "ISO-8859-1";while(str != null) {

System.out.println(str);

headers.add(str);if(str.isEmpty()) {//analysis headers and response http request

String firstLine = headers.get(0);

String parts[]= firstLine.split(" ");

String responseHeader;

String responseBody;

String file;

responseHeader= "HTTP/1.1 200 OK\r\n";

DataOutputStream out= newDataOutputStream(connectedClient.getOutputStream());if (parts[1].equals("/")) {

file= "./index.html";

}else{

file= "." + parts[1];

}

String mimeType;if (file.endsWith(".html")) {

mimeType= MIME_TYPES[0];

}else if(file.endsWith(".jpg")) {

mimeType= MIME_TYPES[1];

}else if(file.endsWith(".png")) {

mimeType= MIME_TYPES[2];

}else if(file.endsWith(".gif")) {

mimeType= MIME_TYPES[3];

}else if(file.endsWith(".css")) {

mimeType= MIME_TYPES[5];

}else if(file.endsWith(".js")) {

mimeType= MIME_TYPES[4];

}else{

mimeType= MIME_TYPES[0];

}try{

File fl= newFile(file);

Long len=fl.length();

responseHeader+= "Content-Length:" + len + "\r\n";

responseHeader+= "Content-Type:" +mimeType;byte[] buf = new byte[len.intValue()];

FileInputStream flin= newFileInputStream(file);

flin.read(buf,0, len.intValue());

responseBody= newString(buf, encoding);

}catch(Exception e) {

connectedClient.close();break;

}

out.writeBytes(responseHeader+ "\r\n\r\n" +responseBody);

connectedClient.close();break;

}

str=bufferedReader.readLine();

}

}

}catch(Exception e) {//do nothing

}

}

}

 类似资料:

相关阅读

相关文章

相关问答