我已经稳定了客户端和服务器之间的套接字连接,但是现在我试图让服务器在他收到特定消息(“ FIM”)时关闭连接,到目前为止,我还没有运气。我一直发送“ FIM”消息,但连接没有关闭
此处提供代码:
class Cliente {
public static void main(String argv[]) throws UnknownHostException, IOException {
InetAddress ip = InetAddress.getLocalHost();
String hostName = ip.getHostName();
Socket meuSocket = new Socket(hostName, 6789);
PrintWriter saida = new PrintWriter(meuSocket.getOutputStream(), true);
BufferedReader digitado = new BufferedReader(new InputStreamReader(System.in));
while (meuSocket.isConnected()) {
String mensagemParaServidor = digitado.readLine();
if (mensagemParaServidor == "FIM") {
meuSocket.close();
break;
}
saida.println(mensagemParaServidor);
}
}
}
class Servidor {
public static final int PORT = 6789;
public static void main(String argv[]) throws IOException {
new Servidor().rodarServidor();
}
public void rodarServidor() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Servidor pronto");
while (true) {
Socket meuSocket = serverSocket.accept();
new ServerThread(meuSocket).start();
}
}
}
public class ServerThread extends Thread {
Socket meuSocket;
ServerThread(Socket meuSocket) {
this.meuSocket = meuSocket;
}
public void run() {
try {
String mensagemRecebida = null;
BufferedReader entrada = new BufferedReader(new InputStreamReader(meuSocket.getInputStream()));
while (((mensagemRecebida = entrada.readLine()) != null)
|| ((mensagemRecebida = entrada.readLine()) != "FIM")) {
System.out.println("Cliente enviou: " + mensagemRecebida);
DataOutputStream saida = new DataOutputStream(meuSocket.getOutputStream());
saida.writeBytes("Obrigado!");
}
System.out.println("Fechando servidor");
meuSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
谢谢!
答案 0 :(得分:0)
请勿将搅拌与==进行比较,而应使用等号。
仅使用readLine是个坏主意。最好将字符串打包成某种消息并发送整个消息。因此,另一端可以确定消息的结尾和开头。例如,第一个字节可以是下一个消息长度。另外,您在ServerThread中两次调用readLine