【问题标题】:stunned at readline socket java惊呆了 readline socket java
【发布时间】:2014-04-07 19:31:54
【问题描述】:

我需要进行“静态”聊天,当我的客户说“PAPO”时,我的服务器需要打印 PAPO 并将 PEPO 发送到客户端打印。 但是我在服务器上的 readLine() 遇到问题,简单地停在这一行。

import java.net.*;
import java.io.*;

public class Servidor {

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(6543);
            do {
                Socket s = server.accept();
                System.out.println("Servidor escutando...");
                BufferedReader entrada = new BufferedReader(
                        new InputStreamReader(s.getInputStream()));
                PrintWriter saida = new PrintWriter(s.getOutputStream());

                System.out.println(entrada.readLine());

                saida.write("PEPO");
                System.out.flush();

                entrada.close();
                saida.close();
                s.close();

            } while (true);
        } catch (UnknownHostException ex) {
            System.out.println("Host desconhecido");
        } catch (IOException ex) {
            System.out.println("Erro na conexao: " + ex.getMessage());
        }
    }
}

客户:

import java.net.*;
import java.io.*;

public class Cliente {

    public static void main(String[] args) {
        try {
            Socket s = new Socket("localhost", 6543);
            do {
                BufferedReader entrada = new BufferedReader(
                        new InputStreamReader(s.getInputStream()));
                PrintWriter saida = new PrintWriter(s.getOutputStream());

                saida.write("PAPO");

                System.out.println(entrada.readLine());


                entrada.close();
                saida.close();
                s.close();
            } while (true);
        } catch (UnknownHostException ex) {
            System.out.println("Host desconhecido");
        } catch (IOException ex) {
            System.out.println("Erro na conexao: " + ex.getMessage());
        }
    }

}

【问题讨论】:

  • 写入后尝试刷新输出流。

标签: java sockets chat message readline


【解决方案1】:

看看你从客户端写了什么:

saida.write("PAPO");

这没有换行符,因此服务器不知道同一行中是否有更多文本。此外,由于您还没有刷新您的 writer,因此可能实际上没有发送任何数据。如果您只是将其更改为:

saida.write("PAPO\n");
saida.flush();

我怀疑你会发现它有效。

但是,我强烈建议您在使用InputStreamReaderOutputStreamWriter 时指定编码,而不仅仅是使用平台默认值。如果您控制两端,UTF-8 通常是一个不错的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多