Search code examples
javaswingsocketsserversocket

How to Bind Port In java Class


I am using Swing and now i want to Allocate one Special port for the Java class which is running in my swing. so how do i bind that port so every time when user run that so there wont be creating new object it will show message that process is already running!! I need to Bind that port to the Process how to do it?

Socket s = new Socket();
s.bind(new InetSocketAddress(9000));

i have bind this address but how to bind it in current class object.?


Solution

  • try to use static variable - this object will be created only once

    private static Socket s = new Socket();
    
    static {
        try {
            s.bind(new InetSocketAddress(9000));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }