0
我希望創建某種類型的路由器,以將來自HTTP客戶端的HTTP請求重定向到servlet(它們預執行協商過程)更多背景信息:我希望從Windows執行身份驗證Windows服務器,通過一個重定向的Unix Web服務器)。使用套接字重定向持久HTTP請求和響應
我的servlet是http://localhost:8080
和我的轉向器是8081
所以,我寫了這個:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Redirect {
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(8081);
Socket s = new Socket("localhost", 8080);
Socket l = ss.accept();
l.setKeepAlive(true);
s.setKeepAlive(true);
OutputStream os = s.getOutputStream();
InputStream is = l.getInputStream();
Thread t1 = new Thread(new MyReader(is, os,"#1"));
t1.start();
InputStream is2 = s.getInputStream();
OutputStream os2 = l.getOutputStream();
Thread t2 = new Thread(new MyReader(is2, os2,"#2"));
t2.start();
}
public static class MyReader implements Runnable {
private InputStream _i;
private OutputStream _o;
private String _id;
public MyReader(InputStream i, OutputStream o, String id) {
_i = i;
_o = o;
_id = id;
}
@Override
public void run() {
try {
int x;
x = _i.read();
while (x != -1) {
System.out.println(_id);
_o.write(x);
_o.flush();
x = _i.read();
}
System.out.println(x);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
它的工作原理適用於大部分的servlet!那麼我的問題是什麼?我的servlet是一個持久的http://en.wikipedia.org/wiki/HTTP_persistent_connection,即它連接=保持活動,並進行整個來回消息跳舞。
我在做什麼錯?我以爲我可以運行兩個MyReader線程,並且它們會阻塞,直到有新信息出現,但是它們會一直阻塞。
這是我的客戶:
public class Client {
public static void main(String[] args) throws IOException {
URL u = new URL("http://localhost:8081/Abc/Def");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
huc.connect();
InputStream is = huc.getInputStream();//The all auth process is done here
//and HttpUrlConnection support it. If I change 8081 to 8080, it works
}