문제

I need to make a "static" chat, when my client say "PAPO", my server need to print PAPO and send PEPO to client print. But im having problem at my readLine() on server, simple stop at this line.

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());
        }
    }
}

Client:

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());
        }
    }

}
도움이 되었습니까?

해결책

Look at what you're writing from the client:

saida.write("PAPO");

That doesn't have a line break, so the server doesn't know whether there's more text coming in the same line. Also, because you haven't flushed your writer, it may be that no data is actually being sent. If you just change it to:

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

I suspect you'll find it works.

However, I would strongly recommend that you specify an encoding when using InputStreamReader and OutputStreamWriter rather than just using the platform default. UTF-8 is usually a good bet if you control both ends.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top