If I understand your problem correctly, you have a non-UI app which runs a server. If the app, for some reason, is not terminated, then when you try to run the app again, you get the error that the server's port is already in use. So, in order to run it again, you need to check if an old instance of the app is alreaydy running and stop it - thus freeing the port - and then run your app.
If this is the case, you can probably achieve this with my suggestion in post #5.