【发布时间】:2020-09-24 05:33:01
【问题描述】:
我正在尝试在本地侦听套接字以用作 HTTP 代理并将所有内容 (TCP) 转发到另一个受相互 TLS 保护的 HTTP 代理。
我环顾四周,但还没有发现可以帮助我实现这个目标的库,所以我选择了原始 java.net.Socket。 但是,套接字和连接管理很麻烦,会导致“套接字关闭”错误,并且大多数情况下根本没有收到响应或连接重置。这是在两个 Socket 之间传递所有内容的正确方法吗?
public class ThreadServer
implements Runnable
{
private final ServerSocket inSocket;
private final SSLSocketFactory socketFactory;
private final String proxyHost;
private final int proxyPort;
public ThreadServer(final SSLSocketFactory socketFactory,
final String proxyHost, final int proxyPort,
final ServerSocket inSocket)
{
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.socketFactory = socketFactory;
this.inSocket = inSocket;
}
private void process(Socket acceptSocket, Socket sendSocket)
throws IOException
{
try (final InputStream inFromClient = acceptSocket.getInputStream();
final OutputStream outToClient = acceptSocket.getOutputStream();
final InputStream inFromServer = sendSocket.getInputStream();
final OutputStream outToServer = sendSocket.getOutputStream())
{
new Thread(() -> {
try {
// can blocking indefinetely so run in a separate Thread
inFromClient.transferTo(outToServer);
} catch (IOException ignored) {}
}).start();
// now copy everything from response back to the client, blocking as wel
inFromServer.transferTo(outToClient);
} finally {
acceptSocket.close();
sendSocket.close();
}
}
@Override
public void run()
{
while (true) {
try {
Socket socket = this.inSocket.accept();
Socket tlsSocket = socketFactory.createSocket(
SocketFactory.getDefault().createSocket(proxyHost, proxyPort), proxyHost, proxyPort, true);
process(socket, tlsSocket);
} catch (IOException ignored) {}
}
}
}
【问题讨论】: