2013-10-11 76 views
0

我的HttpServer與代碼的Java的HttpServer和HttpHandler的和URLConnection保持活躍

HttpServer server; 
server = HttpServer.create(new InetSocketAddress(proxyConfig.port), 0); 
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool()); 
server.createContext("/", new SMPBClientHandler()); 
server.start(); 

和代碼SMPBClientHandler部分:

public class SMPBClientHandler implements HttpHandler { 
    @Override 
    public void handle(final HttpExchange exchange) throws IOException { 
    //Some code work with data 
    exchange.close(); 
    } 
} 

在客戶端有連接

HttpURLConnection retHttpURLConnection = (HttpURLConnection) urlToConnect.openConnection(); 
     retHttpURLConnection.setRequestMethod("POST"); 
//Some work code and then 
os = connection.getOutputStream(); 
//Some work with response 
os.close(); 

但當我使用exchange.close();連接每次關閉,然後我做服務器端的retHttpURLConnection.openConnection()調用句柄(最終HttpExchange交換)函數。

如何創建保持連接?

我想要一個用戶=一個連接。

現在我有一個用戶=很多連接。

回答

1

您不應該關閉服務器端的響應輸出流,而不是交換機本身?

public class SMPBClientHandler implements HttpHandler { 
    @Override 
    public void handle(final HttpExchange exchange) throws IOException { 
     OutputStream os = exchange.getResponseBody(); 
     os.write("response".getBytes()); 
     os.close(); 
    } 
} 

並於客戶端

HttpURLConnection retHttpURLConnection = (HttpURLConnection) urlToConnect.openConnection(); 
retHttpURLConnection.setRequestMethod("POST"); 
retHttpURLConnection.setRequestProperty("Connection", "keep-alive"); 
//Some work code and then 
os = connection.getOutputStream(); 
//Some work with response 
os.close();