使用套接字重定向持久HTTP请求和响应



我希望创建某种路由器,将HTTP请求从HTTP客户端重定向到servlet(它们执行协商过程)。更多背景:我想做一个从windows到windows服务器的授权,通过一个重定向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);
              }

相关内容

  • 没有找到相关文章

最新更新