比特币池开采的地层连接

时间:2017-04-23 19:08:30

标签: java json bitcoin

我使用stratum协议编写了​​一个在池中挖掘的比特币矿工(参见文档here

stratum协议使用JSON-RPC 2.0进行编码,根据JSON-RPC 2.0规范(规范here),我应该使用套接字创建与池的连接。

我的问题是我似乎无法从池中收到回复。 JSON-RPC 2.0指出,对于我发送的每个Request对象,我都必须收到回复。

这是我的代码:

public static void main(String[] args) 
{
    connectToPool("stratum.slushpool.com", 3333);
}    
static void connectToPool(String host, int port)
{
    try
    {
        InetAddress address = InetAddress.getByName(host);
        out.println("Atempting to connect to " + address.toString() + " on port " + port + ".");

        socket = new Socket(address, port);
        String message1 = "{\"jsonrpc\" : \"2.0\", \"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}";

        PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        output.write((message1 + "\\n"));
        out.println(input.readLine());//Hangs here.
    }
    catch (IOException e) 
    {
        out.println(e.getMessage());
        out.println("Error. Can't connect to Pool.");
        System.exit(-2);
    }
}

2 个答案:

答案 0 :(得分:2)

经过几个小时的修修补补,我找到了解决方案。 显然JSON字符串不应该有任何空格。所以而不是:

String message1 = "{\"jsonrpc\" : \"2.0\", \"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}";

应该是:

String message1 = "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[]}";

答案 1 :(得分:0)

好的,..这是完整的运行代码。享受。

import java.io.PrintWriter;
import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class StratumSubscribe {

public static void main(String[] args)
{
connectToPool("sha256.hk.nicehash.com", 3334);
}

static void connectToPool(String host, int port)
{
try
{
    InetAddress address = InetAddress.getByName(host);
    System.out.println("Atempting to connect to " + address.toString() + " on port " + port + ".");

Socket socket = new Socket(address, port);
String message1 = "{\"id\":1,\"method\":\"mining.subscribe\",\"params\":[]}";

PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println((message1));
System.out.println(input.readLine());//Hangs here.
}
catch (IOException e)
{
    System.out.println(e.getMessage());
    System.out.println("Error. Can't connect to Pool.");
    System.exit(-2);
}
}
}