æ¥ä»ããããã ãã©æ°ã«ãããªã
(ä»ã¯11/23)
JDK6ã«HTTPãµã¼ãã¼ã¯ã©ã¹ãç¨æããã¦ãã¨ãããã¨ã§ãããã使ã£ã¦éçãã¡ã¤ã«å°ç¨ã®ç°¡åãªWebãµã¼ãã¼ä½ã£ã¦ã¿ã¾ããã
package webserver; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; public class SimpleWebServer { private static final int PORT = 8880; private static final String DOCUMENT_ROOT = "C:\\Users\\kishida\\Documents\\web"; public static void main(String[] args) throws IOException{ //contenttypeãç»é²ãã¦ãã final Map<String, String> contentTypes = new HashMap<String, String>(); contentTypes.put("html", "text/html"); contentTypes.put("jpg", "image/jpeg"); contentTypes.put("png", "image/png"); contentTypes.put("gif", "image/gif"); contentTypes.put("css", "text/css"); //ããã¥ã¡ã³ãã«ã¼ã final File root = new File(DOCUMENT_ROOT); //ãµã¼ãã¼æºå HttpServer server = HttpServer.create( new InetSocketAddress("localhost", PORT), 0); //å¿çå¦ç server.createContext("/", new HttpHandler() { public void handle(HttpExchange he) throws IOException { String path = he.getRequestURI().getPath(); File f = new File(root, path); if(!f.exists()){ //ãã¡ã¤ã«ããªã he.sendResponseHeaders(404, 0); sendMessage(he.getResponseBody(), "not found."); return; } if(f.isDirectory()){ File indexFile = new File(f, "index.html"); if(!indexFile.exists()){ //ãã£ã¬ã¯ããªã¯è¦ããªã he.sendResponseHeaders(403, 0); sendMessage(he.getResponseBody(), "fobbiden."); return; } f = indexFile; } int idx = path.lastIndexOf("."); if(idx >= 0){ //æ¡å¼µåããmimeã¿ã¤ããåºå String ext = path.substring(idx + 1); if(contentTypes.containsKey(ext)){ he.getResponseHeaders().add( "Content-Type", contentTypes.get(ext)); } } he.sendResponseHeaders(200, f.length()); //ãã¡ã¤ã«å 容ãè¿ã InputStream is = new FileInputStream(f); OutputStream res = he.getResponseBody(); try{ byte[] buf = new byte[1024]; int len; while((len = is.read(buf)) >= 0){ res.write(buf, 0, len); } }finally{ res.close(); is.close(); } } }); server.start(); } private static void sendMessage(OutputStream res, String message) throws IOException{ try{ PrintWriter pw = new PrintWriter(res); pw.println(message); pw.close(); }finally{ res.close(); } } }
ããã ãã§ãã
çµæ§ã¾ã¨ãã«åãã®ã§ç¬ã£ã¦ãã¾ãã¾ãã
Socketãç´æ¥ä½¿ãã®ã«ããã¹ã¦ããããã¼ã®æ±ããªããããã£ã¦ãããã®ã楽ã§ããHTTPãããã³ã«ã調ã¹ãå¿
è¦ãããã¾ããã