我正在構建一個Java客戶端應用程序,它需要向服務器發送消息並在接收到響應後。我可以成功發送消息,問題是我無法獲得響應,因爲在嘗試讀取「BufferedReader」時,我得到一個IO異常(「Socked is closed」)。客戶端應用程序套接字在打印後關閉字符串
這是我的代碼,到目前爲止:
public class MyClass {
/**
* @param args the command line arguments
*/
@SuppressWarnings("empty-statement")
public static void main(String[] args) {
JSONObject j = new JSONObject();
try {
j.put("comando", 1);
j.put("versao", 1);
j.put("senha", "c4ca4238a0b923820dcc509a6f75849b");
j.put("usuario", "1");
j.put("deviceId", "1");
} catch (JSONException ex) {
System.out.println("JSON Exception reached");
}
String LoginString = "{comando':1,'versao':1,'senha':'c4ca4238a0b923820dcc509a6f75849b','usuario':'1','deviceId':'1'}";
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("10.1.1.12", 3333);
System.out.println("Connected to the server successfully");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
outToServer.println(j.toString());
outToServer.close();
System.out.println("TO SERVER: " + j.toString());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String resposta = inFromServer.readLine();
System.out.println("FROM SERVER: " + resposta);
clientSocket.close();
} catch (UnknownHostException ex) {
System.out.println("Could not connect to the server [Unknown exception]");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
我知道插座被關閉,因爲的OutToServer.close()但關閉流是發送消息的唯一途徑。我應該如何處理這種情況?
你確定關閉流發送消息的唯一途徑?有flush()方法,甚至沒有必要,因爲您將第二個參數(autoFlush)設置爲true來構建PrintWriter。我無法明白你的觀點。 PS:你有服務器代碼嗎? – gd1