[英]Redirecting persistent HTTP requests and responses using sockets
我希望创建某种路由器,以将HTTP请求从HTTP客户端重定向到Servlet(它们执行协商过程。更多背景:我希望从Windows到Windows Server进行身份验证,通过重定向的Unix Web服务器) 。
我的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
}
尝试在启动t2线程后添加无限等待循环,如下所示
while ( true) {
sleep(1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.