gpt4 book ai didi

使用套接字的 Android 代理

转载 作者:行者123 更新时间:2023-11-29 01:52:48 28 4
gpt4 key购买 nike

我正在尝试在 Android 中创建代理,但我必须使用套接字。我已经阅读了很多教程并提出了以下代码。不幸的是,浏览器似乎没有获得任何数据,一段时间后它显示标准网页,说网页不可用。可能是什么原因?感谢您的帮助。

        ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(9902, 0, InetAddress.getByName("localhost"));
} catch (Exception e) {
e.printStackTrace();
}
if (serverSocket != null) {
while (!Thread.currentThread().isInterrupted()) {
try {
Socket socket = serverSocket.accept();
new Thread(new RunnableToReadSocketData(socket)).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

private class RunnableToReadSocketData implements Runnable {
private final Socket clientSocket;

public RunnableToReadSocketData(Socket socket) {
this.clientSocket = socket;
}

@Override
public void run() {
Socket serverSocket = null;
try {
InputStream streamFromClient = clientSocket.getInputStream();
PrintWriter streamToClient = new PrintWriter(clientSocket.getOutputStream());

StringWriter writer = new StringWriter();
IOUtils.copy(streamFromClient, writer);
String requestString = writer.toString();

int firstSpace = requestString.indexOf(" ");
int secondSpace = requestString.indexOf(" ", ++firstSpace);

String url = requestString.substring(firstSpace, secondSpace);
Uri uri = Uri.parse(url);
String urlWithoutProtocol = uri.getHost();

System.out.println("==============Reading Socket==============\n" + clientSocket.toString() + "\n" + requestString);

serverSocket = new Socket(urlWithoutProtocol, 80);

PrintWriter streamToServer = new PrintWriter(serverSocket.getOutputStream(), true);
streamToServer.write(requestString);
streamToServer.flush();

InputStream streamFromServer = serverSocket.getInputStream();
StringWriter writerResponse = new StringWriter();
IOUtils.copy(streamFromServer, writerResponse);
String responseString = writerResponse.toString();

System.out.println("==============RECEIVED==============\n" + serverSocket.toString() + "\n" + responseString);

streamToClient.write(responseString);
streamToClient.flush();

streamToClient.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
}

if (clientSocket != null) {
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

最佳答案

你做错了。处理完 CONNECT 命令后,您需要启动两个线程来通过连接复制字节,每个方向一个。在发送任何内容之前,不要试图阅读整个请求;同上回应。只需在收到字节时复制字节即可。

当您在一个套接字上读取 EOS 时,关闭另一个套接字以进行输出并退出该线程。如果您已经关闭了从中读取 EOS 的套接字,请关闭两者并退出线程。你需要这个以防任何一端关闭,以正确传播它。

关于使用套接字的 Android 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16973447/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com