简体   繁体   中英

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?

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

Now I am able to connect and read data.

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