我希望创建某种路由器来将 HTTP 请求从 HTTP 客户端重定向到 servlet(它们执行协商过程。更多背景:我希望通过重定向 Unix Web 服务器从 Windows 到 Windows 服务器进行身份验证) .
我的 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,也就是说它执行 connection=keep-alive 并执行整个来回消息传递。
我究竟做错了什么?我以为我可以运行两个 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
}