Search code examples
javasocketsclientinputstreambufferedreader

Java socket issue with client and server


I am having an issue comparing the string that is sent from the client to the server. I am trying to read in the message "HELLO" from the client and then respond with hello back from the server. My issue is that when I get to my if statement in the server class I am always hitting the else. I believe I am having trouble understanding which lines are collecting data or just printing. Going to do some research in the mean time, I want to learn this good. Any idea as to why, thank you in advance?

Server class:

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

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(4200);
            System.out.println("The Server is waiting for a client on port 4200");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        //Confirms that the message was received
        System.out.println(message);

            if(message == "HELLO")
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Received our hello message.");
            }
            else
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Did not receive your hello message");
            }
    }

}

Client class:

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

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();
    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("cmps329.csit.selu.edu", 4200);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        ps.println("HELLO");
        //Reads and displays response from server
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        System.out.println(message);        
    }

}

Solution

  • Use

    if (message.equals("HELLO"))
    

    See How do I compare strings in Java? for the why.