0

I have been trying to send messages from a server to my application. I am using application "Simple Socket Tester" to create a server and send UTF-8 messages to the application. I never got the messages on my application and when I debugged the app it gets stuck on the line "mServerMessage= mBufferIn.readLine();" and never gets past it. So it seems it is not able to read the message. When I pause the debugger I come to "LocalSocketImpl.java" where it is stuck on "private native FileDescriptor accept". What can I do to prevent this?

My TCP Client:

public TcpClient(OnMessageReceived listener) {
    mMessageListener = listener;

}

/**
 * Sends the message entered by client to the server
 *
 * @param message text entered by client
 */
public void sendMessage(String message) {
    if (mBufferOut != null && !mBufferOut.checkError()) {
        mBufferOut.println(message);
        mBufferOut.flush();
    }
}


/**
 * Close the connection and release the members
 */
public void stopClient() {

    mRun = false;

    if (mBufferOut != null) {
        mBufferOut.flush();
        mBufferOut.close();
    }

    mMessageListener = null;
    mBufferIn = null;
    mBufferOut = null;
    mServerMessage = null;
}

public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVER_PORT);

        try {

            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            sendMessage("hi");

            //receives the message which the server sends back
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));



            //in this while the client listens for the messages sent by the server
            while (mRun) {

                mServerMessage = mBufferIn.readLine();
                System.out.println(mServerMessage);

                if (mServerMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(mServerMessage);
                }

            }

            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
    public void messageReceived(String message);
}

}

Kspr
  • 665
  • 7
  • 19

1 Answers1

1

The string that you receive must have '\n' at the end. The readLine method will stop reading or will wait for the stream until it reads a '\n'.

bmdelacruz
  • 2,366
  • 1
  • 19
  • 26
  • Do you know if there is a way to read data that does not end with a new line? Like another command than readLine()? – Kspr Apr 10 '17 at 10:56
  • I'd recommend you no.8 on this [answer](http://stackoverflow.com/a/35446009/6396174). – bmdelacruz Apr 10 '17 at 12:01
  • Thank you for your help, but I now realise that I don't think this will work. It is because the server sends JSON object which I have to parse. I am sorry for bothering you with a lot of questions, but you do not happen to know how to do that? – Kspr Apr 10 '17 at 12:02
  • The data that is being sent looks like this: {"d":{temp_mC";33416,"humidity_ppm"...more data....}} – Kspr Apr 10 '17 at 12:04
  • Perform the method on my previous comment to get the json string. Then use a json library like jsonsimple to parse it. Here's an [article](http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/) that might help you choose a json library. – bmdelacruz Apr 10 '17 at 12:06
  • When I implement the method, the application goes through the while loop the first time and gets the entire message. Then it does not leave the while loop but gets stuck in "Application running" when trying result.write(buffer, 0, length); a second time . Why might that be? – Kspr Apr 10 '17 at 12:22
  • That method should not be blocking. I'm sorry but I have no idea. – bmdelacruz Apr 10 '17 at 12:37
  • It's okay thank you! Do you know what would be the consequence of removing the while loop? – Kspr Apr 10 '17 at 12:46
  • You'll not be able to get all the data from the stream especially if the data you're expecting is larger than the buffer. – bmdelacruz Apr 10 '17 at 13:08
  • I realised my problem, the application get's stuck inside the while loop since it is waiting for new data. The problem is that it does not return the previous data but it takes the next data and adds into the result. Any idea how to get around this? – Kspr Apr 10 '17 at 13:16