我希望创建一种某种类型的路由器来将HTTP请求从HTTP客户端重定向到servlet(它们预先形成一个协商过程。更多背景:我希望从Windows到Windows服务器进行身份验证,通过重定向的Unix网络服务器)。
我的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,就是它连接= 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
}
答案 0 :(得分:0)
尝试在启动t2线程后添加无限等待循环,如下所示
while ( true) {
sleep(1000);
}