Skip to content
Advertisement

Need to run .jar from console for it to work

I have a java application. I’m using eclipse to write, compile and create a runnable .jar.

The program is used to discover OCF devices.

It uses UDP and multicast.

Multicast code

public static void sendMulticast(byte[] data) throws Exception{
        DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
        msocket.send(pack);
    }
public static byte[] recieveMulticast(int timeout) throws Exception{
        DatagramPacket packet;
        byte[] data = new byte[AppConfig.ocf_buffer_size];

        packet = new DatagramPacket(data, data.length);
        msocket.setSoTimeout(timeout);
        msocket.receive(packet);

        return data;
    }

The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.

But when I start it with a double click, it doesn’t work.

When started from console, it finds my test device in less then a second. When started with a double click it doesn’t find it ever.

I haven’t tested it on Windows yet, but the problem remains on Linux all the same.

What is the difference when you start .jar from console or by double clicking? Why is it effecting messages on multicast?

I’m using “Package required libraries into generated JAR”. I’m using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work? I would understand if I used sudo, but I didn’t.

Advertisement

Answer

The problem was in current location, system property

user.dir

This is the first function I call in my main. It doesn’t work from eclipse, so I’ll put an argument for disabling it (it will be disabled only during development).

static void setCurrentDir() throws URISyntaxException{
    String s;
    s = ESP8266_Configurator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
    s = s.substring(0, s.lastIndexOf('/'));
    System.setProperty("user.dir",s);
}

I hope this helps someone. Code should be exported with extracted libraries, not packaged, otherwise it doesn’t work.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement