简体   繁体   中英

Java object destruction with socket connection

So i have a Client class with a socket connection. When a client connects to the server i start by doing a read on that socket to get so information about the client. Then i move the client to a table that has all the connected clients (those who sent their information). Then main socket on which i listen for new connections is where i create clients. The problem is that i am not sure when and if an object with a pending read on a socket is destroyed. My current strategy is having a second table holding all the clients that have not sent their information yet (the unconnected clients if you will). And once a clients sends his information i move him from the unconnected table to the connected table. I really hate this method. I want to simply create the client in the accept callback without adding it to a table. And once the information is received move the client to the connected table.

my Current implementation:

myMainChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() 
        {
                public void completed(final AsynchronousSocketChannel ch, void att) 
                {
                    // accept the next connection
                    myMainChannel.accept(null, this);
                    //add client to unconnected table
                    allUnconnectedClients.put(ch, new Client(ch));
                }
                public void failed(Throwable exc, Void att) 
                {                       
                    exc.printStackTrace();  
                }

         });

Inside the constructor of the client is the first read operation.

what id like to do is simply create the client without adding it to the table. So in other words repalce this:

allUnconnectedClients.put(ch, new Client(ch));

with this:

new Client(ch);

I know it's kinda weird just creating a local variable without using it but there is a read timeout (inside the constructor) that will close everything if nothing is received within 5 seconds.

Since you probably would be waiting for either a read or a write at any given time you can use the read/write methods that accept an attachment + completion handler at any given time. Your Client would be the attachment. The handler would be responsible to register the next read or write callback. If it doesn't then the client would become eligible for garbage collection.

Think of it as continuation passing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM