首先,我为我的英语道歉。我正在尝试使用Java建立客户端 - 服务器连接,但是从服务器获取响应时遇到问题。当我先关闭服务器时,客户端将收到服务器的响应。如果我先关闭客户端,没有任何反应。
以下是服务器的代码:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"8859_1"),1024);
DataOutputStream sendToClient= new DataOutputStream(socket.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(input.readLine());
if(sb.toString().equalsIgnoreCase("lamoyenne")) {
System.out.println(Esclave.moyenneTarif());
sendToClient.writeBytes(String.valueOf(Esclave.moyenneTarif()));
}
if(sb.toString().equalsIgnoreCase("nombrelieuentre100et200")) {
System.out.println(Esclave.nombreLieuEntre100et200());
sendToClient.writeBytes(String.valueOf(Esclave.nombreLieuEntre100et200()));
}
else {
System.out.println(Esclave.tarifParLieu(sb.toString()));
sendToClient.writeBytes(String.valueOf(Esclave.tarifParLieu(sb.toString())));
}
以下是客户端的代码:
System.out.println("Type in: ");
this.connexion = new Socket(InetAddress.getLocalHost(),44000);
Writer output = new OutputStreamWriter(connexion.getOutputStream(), "8859_1");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
this.line = in.readLine();
//DataOutputStream sendToServer = new DataOutputStream(connexion.getOutputStream(),"8859_1");
//sendToServer.writeBytes(this.line+'\n');
output.write(this.line);
output.flush();
connexion.shutdownOutput();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
String temp = inFromServer.readLine();
System.out.println("FROM SERVER: "+ temp);