2013-10-21 85 views
0

我想寫代碼讓客戶端發送一個字符串到服務器,服務器打印字符串並回復一個字符串,然後客戶端打印字符串服務器回覆。
我的服務器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)...」的代碼,那沒問題。

+0

所以你能解釋一下發生了什麼 –

+0

你發送newLine嗎? – Fildor

+0

「public String readLine() 讀取一行文本。行被認爲由換行符('\ n'),回車符('\ r')或後跟回車符立即通過換行。「 - > http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine() – Fildor

回答

1

你應該在其中寫入流的字符串末尾添加"\r\n"

例如:

客戶端:

string = "end"; 
    out.write(string + "\r\n"); 
    out.flush(); 

服務器:

out.write("to end" + "\r\n"); 
    out.flush(); 
    out.close(); 
    System.out.println("end"); 
       // break; 
+0

它不起作用 – wmmj23

+0

我試過了,它在ecplise中運行良好。可以告訴我你的IDE和什麼樣的OS – shadow

0

我沒有看到服務器響應。 你做

System.out.println("br: " + string); 

但不是

out.write(string); 
out.flush(); 
0

Appand 「\ n」 來結束從服務器的響應的。

outToClient.writeBytes(sb.toString() + "\n"); 
0

您正在閱讀的文章,但您並未撰寫文章。添加一個換行符,或致電BufferedReader.newLine().

相關問題