Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7921787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T16:42:56+00:00 2026-06-03T16:42:56+00:00

I have created this asynchronous client socket that connects to a server and keeps

  • 0

I have created this asynchronous client socket that connects to a server and keeps the connection open at all times and auto reconnects when disconnected from the server.

Anyway my problem is this :on initializing the connection I register the operation as a connect operation (SelectionKey.OP_Connect).

Now when I iterate between the selected keys of the selector, I am expecting it to enter the control statement isconnectable and change the operation as seen in the control statement.

unfortunately I’m not getting any selected keys whatsoever. Where could I be going wrong?

        import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;



    /*
     * @author kewin
     */
    public class clientEvent implements Runnable{
        private static volatile boolean connected=false;
        private SocketChannel channel;
        private Selector selector;
        private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
        private QueueData Qdata;
        private SelectionKey selectKey;



        private  void initiateConnection() {
    try {
    selector= Selector.open();//initializes the Selector Thread
    channel = SocketChannel.open();
    channel.configureBlocking(false);
    channel.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"),2000));
    Thread.sleep(50);//Sleeps for a few Seconds to allow decent connection completion
    channel.register(selector,SelectionKey.OP_CONNECT);//Registers the channel with the a selector and a selection key
    if(channel.finishConnect())/*checks whether the connection is finished*/{
        channel.register(selector,SelectionKey.OP_READ);//Registers the channel with the a selector and a selection key
        connected=true;}
   } catch(Exception ex){connected=false;} 
 }


        private void ConnectAndMonitor(){
           while(true){
            try {
               readBuffer.clear();
               channel.read(readBuffer);
            } catch (Exception ex) {
                    connected=false
                try {
                    channel.close()
                    selector.close();
                } catch (Exception e) {         
                }
                   if(!connected){
                    initiateConnection();
                    connected=true;
               }
            }
           }
        }


        @Override
        public void run() {
            try{
                new Thread(){@Override public void run(){ConnectAndMonitor()}}.start(); 

                while(true){
                   if(!connected){
                       System.out.println("not connected");
                       Thread.sleep(500);
                   }
                   else{
                        selector.selectNow();
                                       Set Keys=selector.keys();
                                       Iterator iterator =Keys.iterator();
                        while(iterator.hasNext()){
                            SelectionKey key=(SelectionKey)iterator.next();

                            if(key.isConnectable()){
                                channel.register(selector,SelectionKey.OP_READ);
                                System.out.println("Connectable");
                                break;
                            }

                            if(key.isReadable()){
                                channel.register(selector,SelectionKey.OP_WRITE);
                                System.out.println("Readable");
                                break;
                            }

                            if(key.isWritable()){
                                channel.register(selector,SelectionKey.OP_CONNECT);
                                System.out.println("Writable");
                                break;
                            }
                            System.out.println("<<<<<<<<<>>>>>>>>>>>>");

                       }

                        Thread.sleep(1000);
                   }
                }
            }
            catch(Exception ex){
            }
        }

        public static void main(String[] args){
            new Thread(new clientEvent()).start();
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T16:43:00+00:00Added an answer on June 3, 2026 at 4:43 pm

    If you do the connect in blocking mode it blocks and completes during the method call, so if you subsequently register it for OP_CONNECT, isConnectable() will never be true.

    So if you must have non-blocking connects, which NB your code is already doing without, put the channel into non-blocking mode first, issue the connect(), register for OP_CONNECT, then when it fires and `finishConnect() returns true, deregister OP_CONNECT and register something else, or as you are a client more probably just start sending requests.

    EDIT: Your edited code is incorrect in the following ways:

    1. Remove the Thread.sleep().
    2. Move the finishConnect() call to the isConnected() case of your select loop.
    3. When OP_CONNECT/isConnectable() fires, deregister OP_CONNECT.
    4. Remove the if(!connected) test.

    Most of this I have already said above. At the moment you are (a) giving the connection time to complete, (b) completing it, (c) waiting in the select loop for it to complete, (d) never deregistering OP_CONNECT even though you aren’t interested in it any more, (e) never executing select() if you don’t have a connection, and (f) trying to find completed connections in the select() loop. This doesn’t make any sense whatsoever.

    On the other hand if you don’t mind waiting for the connection to complete inline where you are creating it, why do it in non-blocking mode at all? Do it in blocking mode, then configureBlocking(false), then register for OP_READ/OP_WRITE and forget about OP_CONNECT, isConnectable(), and finishConnect() altogether.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an asynchronous client and server application that wrap OpenSSL. Once created, they
I created a server and generated my client as an asynchronous one. So when
I have created an Html 5 page that provides important server-side functionality. Unfortunately, it
I have an asynchronous socket listener class like this: using System; using System.Collections.Generic; using
I have been asked to write a class that connects to a server, asynchronously
I have created this report using BIRT and phpjavabridge <?php header(Content-type: application/pdf); header(Content-Disposition: inline;
I have created this Fiddle with this code: This is my problem I want
I have created this function to check abecedarian with while loop (A word is
I'm a newbie starting to learn Ruby. I have created this code, however it
I have created something like this and this . In effect I have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.