gpt4 book ai didi

java - 从 Android 到 Node.js 服务器的持久 HTTP 连接

转载 作者:行者123 更新时间:2023-12-01 09:21:43 25 4
gpt4 key购买 nike

我正在尝试实现一个小型通信方案,用于处理从 Android 设备到 Node.js 服务器的 HTTP 请求。使用当前代码,Android 端在收到 header 的响应后关闭连接。

Java:

public String doInBackground(Void... params) {
URL url = new URL("http://" + mServer.getHost() + ":" + mServer.getPort() + "/" + mPath);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(TIMEOUT);
http.setRequestMethod("POST");
http.setDoOutput(true);
http.connect();

OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(mJson);
writer.flush();
writer.close();

mResponseCode = http.getResponseCode();
if (mResponseCode != 200) {
http.disconnect();
return "";
}

InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);

char[] chars = new char[BUF_SIZE];
int size = br.read(chars);

String response = new String(chars).substring(0, size);
//http.disconnect();
return response;
}

Node :

this.socket = http.createServer((req, res) => {

req.on('data', (chunk) => {
this.log.info("DATA");
obj = JSON.parse(chunk.toString());
});

req.on('close', () => {
this.log.info("CLOSE");
});

req.on('connection', (socket) => {
this.log.info("CONNECTION");
});

req.on('end', () => {
this.log.info("END");
});
});

this.socket.listen(this.port, this.host);

此外, Node 端的 connection 事件永远不会被调用,每个请求都直接通过管道传输到 data 事件中。

有没有办法建立持久的 HTTP 连接,以便 Node 服务器可以在连接运行时跟踪它,直到 Android 端再次关闭它?

最佳答案

Socket.io似乎是实现从 Android 到 Node.js 服务器的持久连接的合理库。

关于java - 从 Android 到 Node.js 服务器的持久 HTTP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130484/

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