我正在构建一个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()而被关闭,但关闭流是发送消息的唯一方法。我应该如何处理这种情况?
答案 0 :(得分:2)
flush()
附带{p> new PrintWriter(, true)
时,情况并非如此。
真正的问题是,您正在关闭PrintWriter outToServer
封装基础InputStream
,Socket
来自outToServer
。
当你关闭flush()
时,你正在关闭整个套接字。
您必须使用Socket#shutdownOutput()。
如果您想保持套接字的输入/输出通道以进行进一步的通信,您甚至不必关闭输出。
writeXXX
时, writeXXX
。那些final Socket socket = new Socket(...);
try {
final PrintStream out = new PrintStream(socket.getOutputStream());
// write here
out.flush(); // this is important.
socket.shutdownOutput(); // half closing
// socket is still alive
// read input here
} finally {
socket.close();
}
实际上并不意味着你将这些字节和字符发送到套接字的另一端。
您可能必须关闭输出,仅输出,以通知您发送所有必须发送的服务器。这实际上是服务器端套接字的需求。
{{1}}
答案 1 :(得分:1)
尝试拨打outToServer.flush()
这将尝试从缓冲区中清除数据,尽管它仍不能保证它将被发送。