javaandroidsocketssslsocketfactory

Not able to read data from SocketChannel


We have a server with https and which runs on port 443. I want to read bytes form server. I am using following code.

private void openAndConfigureChannel(Selector sel) throws IOException {
        SSLSocketFactory factory =
                (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket =
                (SSLSocket) factory.createSocket(address,port);

        sslSocket.startHandshake();
        SocketChannel channel = SocketChannel.open();
        channel.connect(sslSocket.getRemoteSocketAddress());
        channel.configureBlocking(false);

        TCLog.i(TAG,"channel:"+channel);

        //channel.configureBlocking(false);
        channel.register(sel, channel.validOps());
    }

and while reading data

private byte[] readData(SelectionKey key) throws Exception {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        buf.clear();
        if (socketChannel .read(buf) == -1) {
            socketChannel .close();
            Log.i(TAG, "Error during read operation");
        }
        buf.flip();
        byte[] array = buf.array();
        int toPosition = buf.limit();
        byte[] subarray = ArrayUtils.subarray(array, 0, toPosition);
        return subarray;
    }

It gives me exception as Connection reset by peer. On line socketChannel .read().

Event I have tried with InetSocketAddress but still no luck Can somebody tell me how to do this?


Solution

  • I have Followed this link. And suggestion given by EJP.

    Now I am able to connect and read data.