JSON本文で応答を受信したときに同様の問題が発生しました。いくつかの実験の後、私はそのプログラムが体を読んでいる間にぶら下がっているのを検出しました。そこで、ヘッダーからContent-Lengthを読み取り、空白行(ヘッダーと本文の間)の後で停止し、その後に必要な文字のみを読み取ることで、これを解決しました。コードは次のとおりです。
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class TelegramSocketClient {
private final String CONTENT_LEN = "Content-Length:";
Socket clientSocket;
SSLSocket sslSocket;
PrintWriter out;
BufferedReader in;
public void startSSLConnection(String ip, int port) throws IOException {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
sslSocket = (SSLSocket) factory.createSocket(ip, port);
out = new PrintWriter(sslSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(sslSocket.getInputStream(), StandardCharsets.UTF_8));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
String line = null;
int contentLen = 0;
while ((line = in.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
if(line.startsWith(CONTENT_LEN)) {
contentLen = Integer.parseInt(line.substring(CONTENT_LEN.length() +1, line.length()));
}
}
char [] buff = new char[contentLen];
in.read(buff, 0, buff.length);
return new String(buff, 0, buff.length);
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
}