【发布时间】: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