[英]How do I close a socket with a specific message?
I've stabilished a socket connection between a Client and a Server, but now I'm trying to get the Server to close the connection whenever he receives a specific message ("FIM"), so far I've had no luck. 我已经稳定了客户端和服务器之间的套接字连接,但是现在我试图让服务器在他收到特定消息(“ FIM”)时关闭该连接,到目前为止,我还没有走运。 I keep sending the message "FIM" and the connection doesn't close 我不断发送消息“ FIM”,但连接没有关闭
Heres the code: 这是代码:
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();
}
}
}
Thanks! 谢谢!
Never compare stirng with == use equals instead. 请勿将搅拌与==进行比较,而应使用equals。
It's bad idea just use readLine. 不好的主意就是使用readLine。 Better pack your string in some kind of message and send whole message. 最好将字符串打包成某种消息并发送整个消息。 So the other side can figure out the end and the start of the message. 因此,另一端可以确定消息的结尾和开头。 For example the first byte can be the next message length. 例如,第一个字节可以是下一个消息长度。 Also you are calling readLine twice in ServerThread 另外,您在ServerThread中两次调用readLine
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.