Java Socket为什么服务器无法回复客户端

时间:2013-10-21 08:16:32

标签: java sockets

我想编写代码让客户端向服务器发送字符串,服务器打印字符串并回复字符串,然后客户端打印字符串服务器回复。
我的服务器

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)...”,则没关系。

4 个答案:

答案 0 :(得分:1)

你应该在写入流的String的末尾添加"\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;

答案 1 :(得分:0)

我没有看到服务器响应。 你做了

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

但不是

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

答案 2 :(得分:0)

Appand“\ n”结束服务器的响应。

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

答案 3 :(得分:0)

你正在读行,但你不是在写行。添加换行符,或致电BufferedReader.newLine().