0

I was trying to use SocketChannel for my Android application. but the issue I am facing is that I am not able to read the response even if I have written to the SocketChannel successfully. Also, I get selKey.isWritable(), selKey.isReadable() and selKey.isConnectable() true simulatneously, how should I handle such a scenario?

Please help me understand where am I going wrong ?

SocketChannel socketChannel = null;

    try {

        // Create client SocketChannel
        socketChannel = SocketChannel.open();

        // nonblocking I/O
        socketChannel.configureBlocking(false);

        // Connection to host port 8000
        socketChannel.connect(new InetSocketAddress(pTargetURL,pTargetPort));

        // Create selector
        Selector selector = Selector.open();

        // Record to selector (OP_CONNECT type)
        socketChannel.register(selector, SelectionKey.OP_CONNECT);


        // Wait for events
        while (true) {

            selector.select();

            // Get list of selection keys with pending events
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            // Process each key at a time
            while (iterator.hasNext()) {

                // Get the selection key
                SelectionKey selKey = (SelectionKey)iterator.next();

                // Remove it from the list to indicate that it is being processed
                iterator.remove();

                if (selKey.isValid() && selKey.isConnectable()) {

                    // Get channel with connection request
                    SocketChannel sChannel = (SocketChannel)selKey.channel();

                    boolean success = sChannel.finishConnect();

                    if (success) {
                        socketChannel.register(selector, SelectionKey.OP_WRITE);
                    }

                    else {

                        // An error occurred; handle it 

                        // Unregister the channel with this selector
                        selKey.cancel();

                    }
                }

                else if(selKey.isValid() && selKey.isWritable()) {

                    SocketChannel sChannel = (SocketChannel)selKey.channel();

                     // See Writing to a SocketChannel
                    ByteBuffer requestBuffer = null;

                    String requestHeader    = pRequestMethod + " /" + pTargetFile + " HTTP/1.1" + "\r\n";
                    String requestHost      = "Host: " + pTargetURL + "\r\n";
                    String requestlength    = "Content-Length: " + pRequestXML.length() + "\r\n\r\n";
                    String requestXML       = pRequestXML + "\r\n";

                    String finalRequest     = requestHeader + requestHost + requestlength + requestXML;

                    requestBuffer = ByteBuffer.wrap(finalRequest.getBytes(Charset.forName("UTF-8")));                       
                    sChannel.write(requestBuffer);  

                    socketChannel.register(selector, SelectionKey.OP_READ);

                }
                else if (selKey.isValid() && selKey.isReadable()) {

                    // Get channel with bytes to read
                    SocketChannel sChannel = (SocketChannel)selKey.channel();

                    // See Reading from a SocketChannel
                    ByteBuffer responseBuffer = ByteBuffer.allocate(1024);

                    String responseString = null;

                    while(sChannel.read(responseBuffer) > 0)    {

                        responseString = new String(responseBuffer.array(), Charset.forName("UTF-8"));
                    }
                }                               
            }
        }
    }

    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try {

            socketChannel.close();
        } 
        catch (IOException e) {

            e.printStackTrace();
        }
    }
Mayank
  • 1,099
  • 4
  • 17
  • 44
  • I have already gone through the [question](http://stackoverflow.com/questions/13050848/java-nio-on-android-attempting-to-read-write-while-connection-is-still-pending), and following steps that are mentioned there, still its not working for me. – Mayank Oct 21 '14 at 04:44
  • @EJP can you have a look at my code and let me know what am I doing wrong ? – Mayank Oct 21 '14 at 04:46
  • No, you aren't following the steps that are mentioned there. See my answer there. For a start, if `finishConnect()` returns false, it isn't correct to conclude that error has occurred: there is no reason to cancel the key. You're also not checking for EOS when reading, or [handling zero-length writes when writing](http://stackoverflow.com/questions/23136079/communicating-between-nio-op-read-and-op-write-operations/23145585#23145585). – user207421 Oct 21 '14 at 06:09

0 Answers0