将java.nio.channels.SocketChannel与Selectors一起用于客户端

时间:2014-10-21 03:49:35

标签: java android asynchronous nio socketchannel

我试图将SocketChannel用于我的Android应用程序。但我面临的问题是,即使我已成功写入SocketChannel,我也无法阅读回复。另外,我同时得到selKey.isWritable()selKey.isReadable()selKey.isConnectable(),我应该如何处理这种情况?

请帮助我了解我哪里出错?

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();
        }
    }

0 个答案:

没有答案