0

First of all I know that this is a REALLY COMMON problem and I have surfed all over dozens of publications and posts. They have mostly the same solution. But after hours of trying that still doesn't work for me.

The problem is in sending/receiving text messages - I don't receive any response from server. Its not a HTTP server so I use Socket. I suppose there're could several causes:

  1. Problems with connection initialization;
  2. Possibly process of sending/receiving messages is wrong;
  3. Perhabs I'm building messages by protocol somehow wrong.

Now the code.

Init/open Socket connection:

    private class OpenSocketTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            // Creating InetAddress object from ipNumber passed via constructor from IpGetter class.
            InetAddress serverAddress = InetAddress.getByName(HOST); //also tried instead: socket = new Socket(HOST, PORT);

            // Create a new Socket instance and connect to host
            socket = new Socket(serverAddress, PORT);
            Log.i(TAG, "Socket created: " + HOST + ":" + PORT);

            // Create PrintWriter object for sending messages to server.
            // out = new PrintWriter(socket.getOutputStream(), true); //also tried this
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            //Create BufferedReader object for receiving messages from server.
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Log.d(TAG, "In/Out created");

        } catch (UnknownHostException e) {
            Log.e(TAG, "Don't know about host: " + HOST + ":" +PORT);
            connected = false;
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "Couldn't get I/O for the connection to: " + HOST + ":" +PORT);
            connected = false;
            Log.e(TAG, e.getMessage());
        }
        connected = true;
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (connected) {
            Log.d(TAG, "Connected to TCP server...");
        }
        super.onPostExecute(result);
    }
}

Send and Receive messages:

    public class ServerSendMessageTask extends AsyncTask<Void, Void, Void> {
    private String message;

    public ServerSendMessageTask(String message){
        this.message = message;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if (connected) {
            Log.d(TAG, "Sending command to server: " + message);
            try {
                out.println(message);
                out.flush();

                /**
                 * Alternative for SEND message
                 * Both didn't work.
                 * */
//                    //Send the message to the server
//                    OutputStream os = socket.getOutputStream();
//                    OutputStreamWriter osw = new OutputStreamWriter(os);
//                    BufferedWriter bw = new BufferedWriter(osw);
//                    bw.write(message);
//                    bw.flush();

                Log.d(TAG, "Message was sent: " + message);

                //Listen for the incoming messages while connected = true
                while (connected) {
                    String incomingMessage = in.readLine();
                    if (incomingMessage != null) {
                        //never reach here :(
                        Log.d(TAG, "Received from server string: " + incomingMessage);
                    }
                }

                /**
                 * This is the alternative way to RECEIVE message
                 * Both didn't work for me
                 * */
//                    //Get the return message from the server
//                    InputStream is = socket.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(is);
//                    BufferedReader br = new BufferedReader(isr);
//                    String response = br.readLine();
//                    Log.d(TAG, "Received from server string: " + response);

            } catch (UnknownHostException e) {
                Log.e(TAG, "Don't know about host: " + HOST + ":" +PORT);
                Log.e(TAG, e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, "Couldn't get I/O for the connection to: " + HOST + ":" +PORT);
                Log.e(TAG, e.getMessage());
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void res) {
        super.onPostExecute(res);
    }
}

I open Socket in Activity's onStart() as new OpenSocketTask().execute(); and send message on button click with code new ServerSendMessageTask(message).execute();. Therefore Threads don't "overlap".

Another thing that could be:

I'm trying to send Ping package (see page 6 here) to server. Just to see its working. It looks like this #P#\r\n. So I'm supposed to receive this string if everything's Ok: #AP#\r\n.

Its not really clear about the format in Java therefore I've tried to send different combinations of messages: #P#\r\n, #P#\\r\\n, #P#. No differences.

Could you please point my mistake here?

AnZ
  • 1,040
  • 24
  • 54
  • 1
    You did not tell whats actually happening. So how should we know? – greenapps Jun 17 '15 at 17:17
  • `and send message on button click.`. How? Should we guess? – greenapps Jun 17 '15 at 17:18
  • What kind of server is it? – greenapps Jun 17 '15 at 17:19
  • @greenapps, I'm sorry if I gave not enough information. Basically what happening (according to my Logs trace) is that it successfully opens Socket and Sends message but doesn't receive anything as result. By "successfully" I mean that no exceptions occured. The server itself is a typical Web Server which receives data and handles it (arranges and creates history). I know only IP and PORT of it and a hint from developer: **open Socket and pass data as structured by Protocol (see link in post) text**. About how I send message is simply putting String as parameter (check edited post). – AnZ Jun 17 '15 at 17:46
  • No. That server is not a typical web server. It is not a web server at all as it does not use the http protocol. You are using a Wialon server. You should have stated that in the subject of your post. And then again in the first line of your post. Please edit your post. Do not refer with links to what you have to send and what the response would be but tell it in your post. Please show exactly what you put in String message and how you call the second async task. – greenapps Jun 17 '15 at 17:53
  • 'new ServerSendMessageTask(message).execute();'. Please show exactly what is in message. – greenapps Jun 17 '15 at 18:12
  • @greenapps, I have fixed the post, could you help now? I'm sending as message `#P#\r\n` and expecting to receive `AP#\r\n`. – AnZ Jun 18 '15 at 08:52
  • No don't tell that you are sending as message #P#\r\n. Better show how you initialise message before you start the asynctask. I asked that before. So `String message = "......" ; new ServerSendMessageTask(message).execute();`. What do you filll in for the .....? Be clear! – greenapps Jun 18 '15 at 10:32
  • `and expecting to receive AP#\r\n`. No. You will expect to receive `#AP#\r\n`. – greenapps Jun 18 '15 at 10:34
  • @greenapps, That's just a typo, ok? Ofc it's with #. You could read the question carefully instead of blaming every word. `String message = "#P#\r\n";` from post `also tried to send different combinations of messages: #P#\r\n, #P#\\r\\n, #P#` – AnZ Jun 18 '15 at 10:39
  • Be glad that every typo is mentioned too. And about reading carefully ... who is saying that? Very unfriendly. – greenapps Jun 18 '15 at 10:53
  • Sorry if that sounded offensive – AnZ Jun 18 '15 at 11:06
  • 1
    If you initialise like this: `String message = "#P#\r";` And use PrintWriter with `out.println(message);` then println() will add \n so the wialon server will receive "#P#\r\n". If you want to use BufferedWriter then you should heve a statement `bw.write(message + "\n");` in order for the server to receive "#P#\r\n". – greenapps Jun 18 '15 at 11:17
  • 1
    `while (connected)` remove that. You are sending only one string so one readLine() will be enough getting the answwer. Otherwise it waits endlessly. – greenapps Jun 18 '15 at 11:20
  • @greenapps, `String incomingMessage = in.readLine();`. Not receiving anything. incomingMessage always `null ` for some reason. The same with `String response = br.readLine();` – AnZ Jun 18 '15 at 11:38
  • Ok. But for a Wialon server you normally should login first. Now did you? I see no #L# command in your code. Maybe the server refuses to answer if you are not logged in. If you receive null then the socket was closed. – greenapps Jun 18 '15 at 11:48
  • @greenapps. Yes, I've been thinking about that also. Tried to login first before ping with string `"#L#2.0;358835041690656;NA;AB14A12\r"`. Responce should be `#AL#\r\n`. but problem still the same. Nothing received back. It seems like you send messages into deep space :) – AnZ Jun 18 '15 at 12:14
  • Did a test with a wrong imei and got null for readLine(). So I think your imei (358835041690656) is not registered on the server and the server then closes the connection. – greenapps Jun 18 '15 at 12:33
  • @greenapps, Thats a fake crc16 code. Its wrong and doesnt really matter at this point. I should've received code `#AL#10\r\n` which states about wrong crc16. – AnZ Jun 18 '15 at 12:35
  • Please tell such things right away. With the wrong imei it's actually a litle different as i told first. I receive as answer #AL#0\r\n then which means “0” – connection rejected by server. Upon which the server closes the connection and the next readLine then returns null. – greenapps Jun 18 '15 at 12:40
  • @greenapps, thats weird. Please try this one imei `358835041470656`. This one is registered for sure. And which HOST and PORT are you using between? – AnZ Jun 18 '15 at 12:53
  • Of course i use a different service. So a different HOST and PORT. – greenapps Jun 18 '15 at 13:11
  • Hmm, if you're using the same code I do, then probably the problem is within the server.. – AnZ Jun 18 '15 at 13:12
  • No i do not use your code. I have my own. – greenapps Jun 18 '15 at 13:13
  • 1
    Please adapt your code. `} catch (IOException e) { Log.e(TAG, "Couldn't get I/O for the connection to: " + HOST + ":" +PORT); connected = false; Log.e(TAG, e.getMessage()); } connected = true;` So even if there is a catch... connected will always be true. – greenapps Jun 18 '15 at 13:19
  • I have asked for different server. And now it responds! Seems like that was some not working one before.. Thanks for your patience with newb. You might want post answer so I will accept it. – AnZ Jun 18 '15 at 13:28
  • Please tell if the server responses to #P# messages without logging in? – greenapps Jun 18 '15 at 13:57
  • @greenapps, Nope. Message is sent and its thread freezes after `out.flush();`. Login needs to be first – AnZ Jun 18 '15 at 14:00
  • After 5 mins of waiting thread was terminated. Nothing received back. – AnZ Jun 18 '15 at 14:08

0 Answers0