簡體   English   中英

Java Socket為什么服務器不能回復客戶端

[英]Java Socket why server can not reply client

我想編寫代碼讓客戶端向服務器發送一個字符串,服務器打印字符串並回復一個字符串,然后客戶端打印字符串服務器回復。
我的服務器

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) ...”,就可以了。

您應該在寫入流的字符串末尾添加"\\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;

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

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

但不是

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

將“\\n”附加到服務器響應的末尾。

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

你在讀台詞,但不是在寫台詞。 添加換行符,或調用BufferedReader.newLine().

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM