Android Networking not working [Solved]

I made a small server client program that when a client gets connected, the server then prints that a client has been connected. This works fine with pc. When I run the client side in pc, the server side shows “client connected”. But with the same code when i run it in android, nothing is printed in the server side but the client side still runs in android. So after poking around, I later found out that an exception has been thrown “java.net.SocketException: Permission denied”. I was again trying to find solution for the problem but not sure what to do to get this running. Helping to solve this problem will be much appreciated.



K Out! 8)

ah, solved it. Looks like i only had to add “[xml]<uses-permission android:name=“android.permission.INTERNET”/>[/xml]” in the android manifest file right out side the application node. Hope this helps others.



check out this link http://developer.android.com/reference/android/Manifest.permission.html got some android related stuff for the manifest part.



K Out!

1 Like

We could collect some of these and make checkboxes in the android settings page of a project for this stuff…

1 Like

Networking and prevent phone from sleeping seem to be the most popular ones

[java]"android.permission.WAKE_LOCK"[/java]

1 Like

@normen

Yeah dude that will be kool.

Hi, I have had the same issue but even after putting the permissions in the manifest file i am getting the null pointer exception on my android device when i try to connect it as a client to the server which is on my pc. Can you please share your code for the client side.

I used the following code for client side communication:

package mygame;

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.network.Client;
import com.jme3.network.ClientStateListener;
import com.jme3.network.Message;
import com.jme3.network.Network;
import com.jme3.network.serializing.Serializer;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.system.JmeContext;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;
import java.util.logging.Level;
import sun.rmi.runtime.Log;

/**
*

  • @author ruth
    */
    public class ClientMain extends SimpleApplication implements ClientStateListener {

    private Client myClient;
    Random randomizer;
    public static void main(String[] args) {
    java.util.logging.Logger.getLogger("").setLevel(Level.SEVERE);
    ClientMain app = new ClientMain();
    app.start(JmeContext.Type.Display);
    }

    @Override
    public void simpleInitApp() {
    try {

         myClient = Network.connectToServer("My Cool Game", 1, "server ip address", 2030);
         myClient.start();
    
     } catch (IOException ex) {
       System.out.println("Exception: " + ex);
     }
    
     Serializer.registerClass(CubeMessage.class);
     myClient.addMessageListener(new ClientListener(this,myClient),CubeMessage.class);
     myClient.addClientStateListener(this);
     attachCube("One Cube");
    

// Serializer.registerClass(CubeMessage.class);
// myClient2.addMessageListener(new ClientListener(this,myClient2),CubeMessage.class);
// myClient2.addClientStateListener(this);
//
// attachCube(“One Cube”);
}

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf
                    .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
      System.out.println("Exception: " + ex);
    }
    return "";
}

    /* add demo content */
public void attachCube(String name) {
           
    //int randomNumber = randomizer.nextInt() % 30;

    Box box = new Box(1,1,1);
    Geometry geom = new Geometry(name, box);
    Material mat = new Material(assetManager,
            "Common/MatDefs/Misc/Unshaded.j3md");
    mat.setColor("Color", ColorRGBA.White);
    geom.setMaterial(mat);
    //geom.setLocalTranslation(randomNumber, randomNumber, randomNumber);
    rootNode.attachChild(geom);
}

@Override
public void destroy() {
    try {
        myClient.close();

    } catch (Exception ex) {
    }
    super.destroy();
}

/** Specify what happens when this client connects to server */
public void clientConnected(Client client) {

    /* example -- client-server communication that changes the scene graph */
    CubeMessage CM = new CubeMessage();
    client.send(CM);        
}

/** Specify what happens when this client disconnects from server */
public void clientDisconnected(Client client, DisconnectInfo info) {
}

}

It worked fine on pc but gave a null pointer exception on android

Mentioning a NullPointerException is only really useful if we know the stack trace… and if the top line is in your code then also we need to know what line that is.

Thanx for replying. The error came for this line

myClient.addMessageListener(new ClientListener(this,myClient),CubeMessage.class);

stack trace:

java.lang.NullPointerException
Exception thrown in Thread[GLThread 547,5,main]
at mygame.ClientMain.simpleInit(ClientMain.java:51)
at
com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:226)
at com.jme3.app.AndroidHarness.initialize(AndroidHarness.java:455)
at
com.jme3.system.adnroid.OGLESContext.initInThread(OGLEScontext:java:229)
at
com.jme3.system.android.OGLESContext.onSurfaceCreated(OGLESContext.java:205)
at
android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1501)
at
android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

here is the code for my ClientListener class:

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package mygame;

import com.jme3.material.Material;
import com.jme3.network.Client;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import java.util.concurrent.Callable;

/** WORK IN PROGRESS */

public class ClientListener implements MessageListener {

private ClientMain app;
private Client client;

public void messageReceived(Client source, Message message) {
    
    if (message instanceof GreetingMessage) {
        GreetingMessage greetingMessage =
        (GreetingMessage) message;
        System.out.println("Client #"+source.getId()
        + " received the message: '"
        + greetingMessage.getGreeting() + "'");
        }
    
    if (message instanceof CubeMessage) {
        final CubeMessage cubeMessage = (CubeMessage) message;
        //cubeMessage.setReliable(false);
        app.enqueue(new Callable() {
            public Void call() {
                /* change something in the scene graph from here */
                Material mat = new Material(app.getAssetManager(),
                        "Common/MatDefs/Misc/Unshaded.j3md");
                mat.setColor("Color", cubeMessage.getColor());
                app.getRootNode().getChild(0).setMaterial(mat);
                return null;
            }
        });
    } 
}



/*A custom contructor to inform our client listener about the app. */
public ClientListener(ClientMain app, Client client) {
    this.app = app;
    this.client = client;
}

}

Issue is resolved. It was due to difference in ip format the code for android device was not recognizing ip in this format “fe90:0:0:0:d57d:2e09:7200:c8df%10” i had to give the server ip in standard format i.e. “192.168.4.10”
Thanx

Yeah, in the future, look at that top line… when that line is in your code then the problem is in your code. It’s fine then to show us that code but you’d also need to indicate which line it is as sometimes the line numbers won’t line up with what we see in the forum.

Sure, i will keep that in mind next time.

Hi Guys,

I know this thread is about Android but I’m having a similar problem trying to use networking on IOS.

The code I’m using works fine on Windows, Android, OSX and Linux. It’s just IOS that is failing.

The code is as follows:

public boolean connect(String sUserName, String sPassword) {
try {
Client client = Network.connectToServer(Globals.DEFAULT_SERVER, Globals.DEFAULT_PORT_TCP, Globals.DEFAULT_PORT_UDP);
client.start();
Serializer.registerClass(CCHandshakeMessage.class);
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, “CLIENT STARTED 1”, client);
return true;
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, “ERROR STARTING CLIENT”);
return false;

    }
}

The stack trace is below. Any ideas what it is?

2015-01-25 19:35:30.935 jme-ios[23872:529452] Could not create new iOS Harness object
java/lang/NoSuchFieldError: localPort I not found in java/net/PlainDatagramSocketImpl
at java/net/PlainDatagramSocketImpl.init (native)
at java/net/PlainDatagramSocketImpl. (line 38)
at java/net/DefaultDatagramSocketImplFactory.createDatagramSocketImpl (line 70)
at java/net/DatagramSocket.createImpl (line 316)
at java/net/DatagramSocket. (line 179)
at com/jme3/network/kernel/udp/UdpConnector. (line 51)
at com/jme3/network/Network.connectToServer (line 164)
at com/jme3/network/Network.connectToServer (line 131)
at mygame/Main.connect (line 52)
at mygame/Main.simpleInitApp (line 39)
at com/jme3/app/SimpleApplication.initialize (line 226)
at com/jme3/system/ios/IGLESContext.create (line 162)
at com/jme3/app/Application.start (line 387)
at com/jme3/app/Application.start (line 366)
at com/jme3/app/SimpleApplication.start (line 131)

Aside: This is a completely different issue than anything talked about in this thread, really. This seems like an error in whatever is handling the Java → iOS conversion since the error is deep inside a JDK class.

Yeah, maybe check if you have network access allowed for your app in XCode, otherwise check back with the avian devs here if they know about the error: Google Groupes

Try adding a ProGuard exclusion in ios.properties:

-keep class java.net.PlainDatagramSocketImpl { <fields>; }
# (Or try a * instead of <fields>.)

But be aware that could lead to a very long exclusion list…

Thanks to all replies. I think you are correct ‘revv’. I added the exclusion and it went further than previous attempts.

I dont know a lot about Pro Guard but it does seem to be the main cause of a most of the IOS issues I have come across. Is there a way to switch it off during development? Where is the best place to understand the syntax because there seems to be many different ways of defining an exclusion. Not least of which where to use the wildcard, if at all. When to use public? Implements? How to interpret the error in the stack trace and translate that into a pro-guard exclusion?

I do understand the reason for having it in the final build but it would be nice if it was less of a road block along the way.

Thanks again for your help.

ProGuard Manual:

Keeping everything:

Thanks, if I use the -dontshrink option. Where do I put it?

I tried putting it in the IOS Properties at the start of the options but it didnt work.