ここでは、2秒ごとにサーバーの応答を確認するスレッドを作成していますが、client.monitorResponse()
はreadLine()
メソッドであり、応答が受信されるまで続行されません。 。私は、サーバーに接続されたクライアントソケットを経由して応答を拾っていますソケットストリームでBufferedReaderのタイムアウトを設定する方法
public SocketObject(Socket client, int numberOfClients) throws Exception {
socket = client; // the .accept() socket is passed through
// this is because I assign them ID's for later use (I hold an ArrayList of sockets)
this.clientId = numberOfClients;
// both these are static to the class
outputStream = new PrintWriter(client.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
}
public void sendResponse(String response) {
outputStream.println(response);
}
:
client = new ClientObject("localhost");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
String response = null;
if(!(response = client.monitorResponse()).isEmpty()) {
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 2000, 2000);
私は(client
が確立ソケットがある)ので、などのサーバーを経由して応答を送信しています:
public ClientObject(String hostname) throws IOException {
// socket is static to this class
socket = new Socket(hostname, 4444);
System.out.println("Connected to " + hostname + " on port 4444...");
// both static to this class
outputStream = new PrintWriter(socket.getOutputStream(), true);
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Successfully started a stream on " + hostname);
this.hostname = hostname;
}
public String monitorResponse() throws Exception {
System.out.println("Listening for a response...");
return inputStream.readLine();
}
デバッグコンソールにのみメートルを語っされたらが応答を聞く...出力を表示しますそれはスレッド内でinputStream.readLine()
メソッドを通過しないということです。とにかくBufferedReaderにタイムアウトを追加できますか?私はBufferedReaderを作成する前にソケットに.setSoTimeout()
を追加するような複数のソリューションを試しましたが、指定された時間後に接続/ソケットを閉じることができました。
ご協力いただければ幸いです。
なぜですか?サーバーが応答を送信している場合は、それを読み取る必要があります。タイムアウトを実装すると、次回に応答が読み込まれ、コードが混乱することになります。レスポンスはオプションですか?この場合、アプリケーションプロトコルを誤って設計してしまいました。また、このコードを 'Timer'で実行している場合は、タイムアウトは必要ありません。タイマータスクには他に何もしないでブロックします。実際には、タイマを必要とせず、読み込みループを持つスレッドだけでも必要です。あなたはベルトとブレースをここに着ています。 – EJP
ええ、私はそれが要求を読むことができなかったことを認識しました:それは問題を引き起こしていたものです。 'PrintWriter()'の2番目のパラメータが欠落していました。これは、Socket上で 'getOutputStream()'を使用していたサーバでtrueに設定する必要がありました。 @EJP – KDOT