简单的客户端 - 服务器:在缓冲区中写入之前或之后刷新不起作用

时间:2013-07-29 17:39:47

标签: java client-server flush

我发送字符串到服务器,但是服务器在我发送的字符串之前得到奇怪的字符,我试图在发送之前刷新,发送之后和inicializating输出流变量但是结果是相同的。我听到了很多关于flush()并搜索它,但仍然没有找到如何解决我的问题,也许它很简单,但我无法得到它。

请帮助我!

客户端

    InetAddress endereco = InetAddress.getByName(null); 
    socket= new Socket(endereco, SServer.PORTO);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(new ObjectOutputStream(socket.getOutputStream()),true);

    while(true){                        
        System.out.println("Write your Thoughs.. ");
        Scanner scanner = new Scanner(System.in);
        String Msg = scanner.nextLine();
        System.out.println("I Said: ");
        System.out.println(Msg);
        out.println(Msg);
        out.flush();
        String s  = in.readLine();
        System.out.println("Echo: "+s);

}

// Serve Side

in = new BufferedReader(new  InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    out.flush();
}

private void serve() throws IOException {
                    while(true){
        String s = in.readLine();
        System.out.println("Server Received: " + s);
        if(s.equals("END"))
            break;
        System.out.println("Server Send: " + s);
        out.println(s);     


    }

1 个答案:

答案 0 :(得分:0)

我认为正在发生的事情是,当你编写字符串时,你正在推动它们通过ObjectOutputStream,它试图序列化它们(我认为)。你做的事情比必要的更困难。尝试使用

out = new PrintWriter(socket.getOutputStream());

这样就可以直接通过该行转储文本而不需要额外的东西。