Search code examples
javasocketsnetwork-programmingudpdatagram

How can I make sure that the port I want to use is always available (i.e. not in use)?


Is there a way to force-free ports? The port is passed through args[]. I'm trying to build a server app that waits for UDP packets from multiple devices, so I wan't to make sure that it will always listen to the appropriate port. The data from the packets is to be processed and the results to be written in a DB. I'm using a while(true) loop to keep it listening for new packets. Is it possible that I might have concurrency issues when multiple devices (say 2000) send at once? Is there any other way than using while(true)? Any suggestions?

EDIT (it may not be right on topic) I'm using these methods to convert signed twos complements of 2 bytes and 4 bytes length. I couldn't find a more simple way...

public static Long twosComp16(String str) throws java.lang.Exception
    {
        Long num = Long.valueOf(str, 16);

        int fix = 65536;

        if (num > (fix/2))
            return num - fix;
        else return num;
    }
    public static Long twosComp32(String str) throws java.lang.Exception
    {
        Long num = Long.valueOf(str, 16);

        long fix = 4294967296L;

        if (num > (fix/2))
            return num - fix;
        else return num;
    }

Solution

    1. I don't think you can force free a port. And anyway, that's up to the user. Try to not make choices for the user; ask him/her instead. What makes you think your app is more important than the other one running on that port? ;)
    2. while(running)
    3. If you're going to have heavy processing, make your server spawn a thread for each client instead of having only one processing and the others waiting.