0

I am having a problem with my client server program using sockets in java. So I want the client to send the string "chef", and in the server I want it to send something back if the client sent "chef", otherwise do something else. The problem is the string sent from the client to the server does not match for some odd reason. This is the snip of code I have on the client class, to send the string:

PrintStream PS=new PrintStream(sock.getOutputStream());
PS.println("chef");

In the server I have this snippet:

Socket sock=socket.accept();
InputStreamReader IR=new InputStreamReader(sock.getInputStream());
BufferedReader BR=new BufferedReader(IR);

String message="";



message=BR.readLine();
if (message=="chef")
{
    PrintStream ps=new PrintStream(sock.getOutputStream());
    ps.println("Chef Connected");
}
else
{

    System.out.println(message);
}

So the problem is the server keeps going to the else statement even thought I am sending the correct string "chef". I used System.out.println(message) in the else and it prints the string "chef". So I am very lost at why this is happening. Hopefully I was clear, and any help or clarification would be greatly appreciated.

Kevin Lin
  • 71
  • 2
  • 8
  • 2
    Don't compare strings in Java using `==`, that's for C++. Use `String#equals()` instead. – Tim Biegeleisen Mar 22 '17 at 05:00
  • try doing this, InputStreamReader IR=new InputStreamReader(sock.getInputStream()); while (IR.available()>0){ System.out.println(in.read());} so it will print exactly what u r receiving, maybe its the case of endline characters. You will see character codes, check if you are receiving 99 104 101 102 only or if there are more integers like 10 and 13 in it – Rico Mar 22 '17 at 05:08
  • Tim I was not aware of this and I came from C++, so that would make sense. Also would I do message.equals("chef"); ? – Kevin Lin Mar 22 '17 at 14:00
  • Never mind Tim I got it working thanks for your help, learned something new. – Kevin Lin Mar 22 '17 at 14:11

0 Answers0