2016-03-21 16 views
1

com.sun.net.httpserver sınıfını kullanarak basit bir http sunucusu yazmaya çalışıyorum. Başlangıçta tarayıcıya html dosyası (index.html) gönderiyorum, ancak harici bir css dosyasının nasıl ekleneceğini bilmiyorum. Css kodu html dosyasının içine yerleştirildiğinde çalışır. Biliyorum, bu tarayıcı css dosyası için sunucu soran bir istek göndermeli, ancak bu isteği nasıl alacağından emin değilim ve bu dosyayı tarayıcıya geri göndereceğim. Yardımcı olabilseydim, kodumun bir parçasını eklerim.com.sun.net.httpserver kullanarak css dosyasını nasıl ekleyebilirim?

private void startServer() 
{ 
    try 
    { 
     server = HttpServer.create(new InetSocketAddress(8000), 0); 
    } 
    catch (IOException e) 
    { 
     System.err.println("Exception in class : " + e.getMessage()); 
    } 
    server.createContext("/", new indexHandler()); 
    server.setExecutor(null); 
    server.start(); 
} 

private static class indexHandler implements HttpHandler 
{ 
    public void handle(HttpExchange httpExchange) throws IOException 
    { 
     Headers header = httpExchange.getResponseHeaders(); 
     header.add("Content-Type", "text/html"); 
     sendIndexFile(httpExchange);    
    } 
} 

static private void sendIndexFile(HttpExchange httpExchange) throws IOException 
{ 
    File indexFile = new File(getIndexFilePath()); 
    byte [] indexFileByteArray = new byte[(int)indexFile.length()]; 

    BufferedInputStream requestStream = new BufferedInputStream(new FileInputStream(indexFile)); 
    requestStream.read(indexFileByteArray, 0, indexFileByteArray.length); 

    httpExchange.sendResponseHeaders(200, indexFile.length()); 
    OutputStream responseStream = httpExchange.getResponseBody(); 
    responseStream.write(indexFileByteArray, 0, indexFileByteArray.length); 
    responseStream.close(); 
} 
+0

bu kod satırı ne 'server.createContext ("/", yeni indexHandler());'? –

+0

"/" yolu ile ilişkili bir http içeriği oluşturur. Bu yolun tüm istekleri indexHandler nesnesi tarafından ele alınır. – bizkhit

+0

Bir HTTP sunucusu yazmak istiyorsanız, bir HTTP isteği ile yanıtı arasındaki ilişkinin nasıl olduğunu anlamanız gerekir. Size söylüyorum, bu bir öğretici olacaktır. – Raedwald

cevap

0

Statik içeriği işlemek için yerleşik bir yöntem yoktur. İki seçeneğin var.

nginx gibi statik içerikler için hafif bir web sunucusu kullanın, ancak uygulamanızın dağıtımından daha zor olacaktır. Veya kendi dosya sunum sınıflarınızı yaratın.

int port = 8080; 
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); 
// ... more server contexts 
server.createContext("/static", new StaticFileServer()); 

Ve daha statik dosyaları hizmet verecek sınıf oluşturmak: Bunun için, web sunucusuna yeni bir bağlam oluşturmak zorunda.

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.OutputStream; 

import com.sun.net.httpserver.HttpExchange; 
import com.sun.net.httpserver.HttpHandler; 

@SuppressWarnings("restriction") 
public class StaticFileServer implements HttpHandler { 

    @Override 
    public void handle(HttpExchange exchange) throws IOException { 
     String fileId = exchange.getRequestURI().getPath(); 
     File file = getFile(fileId); 
     if (file == null) { 
      String response = "Error 404 File not found."; 
      exchange.sendResponseHeaders(404, response.length()); 
      OutputStream output = exchange.getResponseBody(); 
      output.write(response.getBytes()); 
      output.flush(); 
      output.close(); 
     } else { 
      exchange.sendResponseHeaders(200, 0); 
      OutputStream output = exchange.getResponseBody(); 
      FileInputStream fs = new FileInputStream(file); 
      final byte[] buffer = new byte[0x10000]; 
      int count = 0; 
      while ((count = fs.read(buffer)) >= 0) { 
       output.write(buffer, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      fs.close(); 
     } 
    } 

    private File getFile(String fileId) { 
     // TODO retrieve the file associated with the id 
     return null; 
    } 
} 

getFile (String fileId) yöntemi için; fileId ile ilişkili dosyayı almanın herhangi bir yolunu uygulayabilirsiniz. İyi bir seçenek, URL hiyerarşisini yansıtan bir dosya yapısı oluşturmaktır. Çok fazla dosyanız yoksa, geçerli kimlik dosyası çiftlerini saklamak için bir HashMap kullanabilirsiniz.

İlgili konular