Java socket programming only receive message from my RPI after I close the connection from RPI side

Viewed 16

I know that bufferedReader.readLine() waits for newline. So from my RPI side, I typed a message "happy\n" and sent it over but my Java is unable to receive it UNTIL I close the connection from RPI side. And the message i received is "happy\n"

How do i fix this?

Side note: I used python for my RPI

Java set up connection with RPI

    public boolean connectToRPi() {
        try {
            socket = new Socket(CommConstants.HOST_ADDRESS, CommConstants.PORT);
            writer = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(socket.getOutputStream())));
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("Connection established with RPi");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

Java receiveMsg function

    public String recieveMsg() {
        String msg = null;
        try {
            msg = reader.readLine();
            return msg;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

Java Main

    public static void main(String[] args) {
        comm.connectToRPi();

        String receiveMsg = null;
        while(receiveMsg == null) {
           receiveMsg = comm.recieveMsg();
        }
        System.out.println("Received Msg = ", receiveMsg + "\n");
        comm.endConnection();
    }
0 Answers
Related