Android Websockets onMessage() never being called even on connection
Asked Answered
A

1

9

I'm using websockets to make a multiplayer game and I need to send multiple types of data across the server but when I connect to the server it's supposed to send back a name and number ("type") and ("data") respectively from the websocket library on connection. I don't need the type but ("data") is vital for the game logic to actually work.

Below is the code I have in my websockets onMessage() function:

@Override
public void onMessage(String message)
{                       
    try 
    {
         JSONObject json = new JSONObject(message);
         if(json.has("type") && json.has("data"))
         {
             Log.d(TAG, json.getString("type"));
             Log.d(TAG, json.getString("data"));
             playerNum = Integer.parseInt(json.getString("data"));
             Log.d(TAG,"Received... Type : " +json.getString("type")+" Data : "+json.getString("data"));
         }
         if(json.has("Player1TurnOver"))
         {
             player1TurnOver = json.getBoolean("Player1TurnOver");
         }

         if(json.has("Word"))
         {
            String b = json.getString("Word");
            bWord = new char[b.length()];
            for(int i = 0; i < b.length(); i++)
            {
                 bWord[i] = b.charAt(i);
            }
         wordLength = bWord.length;
        }
     }
     catch(JSONException e)         
     {                  
     }              
}

But this is never called from the server even though the client has a listener as such:

mClient = new WebSocketClient(URI.create("ws://some_ip:8080/wstest"), new WebSocketClient.Listener()){

And the listener is initialised within the websocket library class

public interface Listener {
    public void onConnect();
    public void onMessage(String message);
    public void onMessage(byte[] data);
    public void onDisconnect(int code, String reason);
    public void onError(Exception error);
}

I can't seem to figure out why this isn't working properly. As it has worked before...

Aniconic answered 15/3, 2014 at 16:20 Comment(1)
Are you using Node.js on server end?Alternator
V
1

Sometimes it is not correctly detected when a device looses internet connection (Java is not that smart in this case ;) )

Apart from this. Could you maybe activate the debug printouts with WebSocketImpl.DEBUG = true;

The lib will automatically send pings to the endpoints at specific interval and if no ping was received it assumes that the endpoint got disconnected!

Vibrant answered 3/4, 2018 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.