我想寫代碼讓客戶端發送一個字符串到服務器,服務器打印字符串並回復一個字符串,然後客戶端打印字符串服務器回覆。
我的服務器Java Socket爲什麼服務器不能回覆客戶端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
我的客戶:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
是有一些出頭錯了嗎?如果我在客戶端類中刪除了「while(true)...」的代碼,那沒問題。
所以你能解釋一下發生了什麼 –
你發送newLine嗎? – Fildor
「public String readLine() 讀取一行文本。行被認爲由換行符('\ n'),回車符('\ r')或後跟回車符立即通過換行。「 - > http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine() – Fildor