Hassan Malaabeh Hassan Malaabeh - 10 days ago 5
Java Question

how to end connection in java socket with "good buy" message

I build a client/server chat in java
and i want to end the connection if one of the client or the server send a "good buy" message
but that not what happened the connection still a live

The code in the client side:

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

public class TCPClient {
public static void main(String[] args) throws Exception {
String message;
String recivedMessage = "h";

Socket clientSoc = new Socket("127.0.0.1",9999);

while(recivedMessage != "good buy") {
System.out.print("Client : ");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSoc.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSoc.getInputStream()));

message = inFromUser.readLine();
outToServer.writeBytes(message + '\n');

recivedMessage = inFromServer.readLine();
System.out.println("Server : " + recivedMessage);
if (recivedMessage == "good buy") {
break;
}
}
if (recivedMessage == "good buy") {
System.out.println("Connection end");
clientSoc.close();
}
}
}


The code in the server side:

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

public class TCPServer {
public static void main(String[] args) throws Exception {
String Message;
String recivedMessage = "h";
ServerSocket welcSoc = new ServerSocket(9999);

while(true){
Socket serverSoc = welcSoc.accept();
while(recivedMessage != "good buy"){
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(serverSoc.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(serverSoc.getOutputStream());
recivedMessage = inFromClient.readLine();
System.out.println("Client : " + recivedMessage);

System.out.print("Server : ");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Message = inFromUser.readLine();
outToClient.writeBytes(Message + '\n');
}
if (recivedMessage == "good buy") {
break;
}
}
if (recivedMessage == "good buy") {
System.out.println("Connection end");
welcSoc.close();
}
}
}

Answer

As you haven't shared the output, I'm assuming everything else is working as expected. For string comparison use : equals

recivedMessage.equals("good buy")

In java == operator compares reference for objects, not the value. Equals method compares object value.

Comments