简体   繁体   中英

Android Socket connection to bitcoin node

I can't get a response from a bitcoin node using a simple java socket on android. I send a version message and wait for a response, but nothing is returned. The code is fairly simple:

private void connect(Peer peer) {
    Log.i(App.TAG, "connect to: " + peer.ip + ":8333");

    InetSocketAddress address = new InetSocketAddress(peer.ip, 8333);
    Socket socket = new Socket();
    try {
        socket.connect(address, 10000);

        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();

        VersionMessage versionMessage = new VersionMessage();
        writeMessage(versionMessage, out);

        readMessage(in);

        Log.i(App.TAG, "Shutting down....");
        out.close();
        in.close();
        socket.close();

    } catch (IOException e) {
        Log.i(App.TAG, "Socket failed to conenct");
    }
}

private void writeMessage(BaseMessage message, OutputStream out) {
    Log.i(App.TAG, "writeMessage: " + message.getCommandName());

    byte[] header   = message.getHeader();
    byte[] payload  = message.getPayload();

    try {
        Log.i(App.TAG,  "header: " + Util.bytesToHexString(header));
        Log.i(App.TAG,  "payload: " + Util.bytesToHexString(payload));

        out.write(header);
        out.write(payload);
    } catch (IOException e) {
        Log.i(App.TAG, "Failed to write message");
    }

}

private void readMessage(InputStream in) throws IOException {
    Log.i(App.TAG, "readMessage");

    while (true) {
        int b = in.read();
        Log.i(App.TAG, "read: " + b);

        if (b == -1) {
            Log.i(App.TAG, "END OF CONNECTION!");
            break;
        }

        response.add(b);

    }
}

The logs from the app are as follows:

connect to: 52.88.14.46:8333
writeMessage: version
header: f9beb4d976657273696f6e00000000006100000061000000
payload: 7c9c000001000000000000005a73788200000000524543495049454e54204950000000000000000000000000000053454e44455220495000000000000000000000000000000000006237646465346163626f657463686169000000000000000000
readMessage
read: -1
END OF CONNECTION!
Shutting down....

Here is a link to the project: https://github.com/boetchain/android-bitcoin-node

checkSum字段是必填字段,其他节点将忽略没有有效校验和的传入消息。

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