0

Possible Duplicate:
DatagramChannel.close() keeps port open on Windows

Trying to get use of DatagramChanned its fine but it is still binding the address after closing it and the function finish execution as the following example.

why this code will print:

Call num: 2

java.net.BindException: Address already in use: bind

 public static void main(String[] args) {

            java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            recever(1);
            recever(2);
        }
    });
}

    static void recever(int c) {
     try {        
        DatagramChannel chdata = DatagramChannel.open();

            int uport = 3111;
            int bufsize = 10;
         chdata.configureBlocking(false);
         Selector selector = Selector.open();

         chdata.bind(new InetSocketAddress(uport));
         ByteBuffer  bytbuf = ByteBuffer.allocate(bufsize);      
            chdata.register(selector, SelectionKey.OP_READ);

     int th = 0;
     int sn;

    while (true) {

        if (selector.select(1000) == 0){
                     System.out.println("\nTimeout");
            break;
        }

        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
           iterator.next();
            iterator.remove();

               bytbuf.clear();
               chdata.receive(bytbuf);
               th++;
               bytbuf.flip();
       //   dealwithincomingbuffer(bytbuf);
          }
       }    
      //  chdata.bind(null);
        chdata.close();

    } catch (IOException ex) {
        System.out.println("Call num: "+c+" \n  "+ex);
    }
  }
}
Community
  • 1
  • 1

1 Answers1

0

You aren't closing your socket in a finally block, and you aren't closing your Selector at all. Ergo there are circumstances in which the socket isn't closed at all.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • what socket if you mean the datagramchannel that i am using i have closed, yes not in finally. and i have to close it in finally and it works now. thank you. – Mohamed Talha Dec 12 '12 at 11:43