Skip to content

Instantly share code, notes, and snippets.

@bitkevin
Last active August 29, 2015 14:10
Show Gist options
  • Save bitkevin/489a3216897c28c952cc to your computer and use it in GitHub Desktop.
Save bitkevin/489a3216897c28c952cc to your computer and use it in GitHub Desktop.
diff --git a/configure.ac b/configure.ac
index 30b9ff5..6ff9680 100644
--- a/configure.ac
+++ b/configure.ac
@@ -400,6 +400,9 @@ if test x$use_upnp != xno; then
)
fi
+ZMQ_LIBS="-lzmq"
+LIBS="$LIBS $ZMQ_LIBS"
+
dnl Check for boost libs
AX_BOOST_BASE
AX_BOOST_SYSTEM
diff --git a/src/init.cpp b/src/init.cpp
index 63e72c6..d1c5ae1 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -383,10 +383,13 @@ std::string LicenseInfo()
static void BlockNotifyCallback(const uint256& hashNewTip)
{
- std::string strCmd = GetArg("-blocknotify", "");
+ // std::string strCmd = GetArg("-blocknotify", "");
+ // boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
+ // boost::thread t(runCommand, strCmd); // thread runs free
- boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
- boost::thread t(runCommand, strCmd); // thread runs free
+ std::string zmqLocalUri = GetArg("-blocknotify", "");
+ std::string blockHash = hashNewTip.ToString();
+ boost::thread t(zmqBlockNotify, blockHash, zmqLocalUri);
}
struct CImportingNow
diff --git a/src/util.cpp b/src/util.cpp
index 0cdf4e6..98ec5ca 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -16,6 +16,8 @@
#include "utilstrencodings.h"
#include "utiltime.h"
+#include "zmq.hpp"
+
#include <stdarg.h>
#ifndef WIN32
@@ -687,6 +689,27 @@ void runCommand(std::string strCommand)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
+void zmqBlockNotify(const std::string &blockHash, const std::string &zmqLocalUri)
+{
+ zmq::context_t zContext(1/* io.threads */);
+ zmq::socket_t zSocket(zContext, ZMQ_PUSH);
+ zSocket.connect(zmqLocalUri.c_str());
+
+ // ZMQ_LINGER: 设置延时,socket调用close后,依然留存的时间,单位:毫秒
+ // 默认是-1:一直留存,会导致 zContext 无法关闭,并阻塞
+ int zmqLinger = 3000;
+ zSocket.setsockopt(ZMQ_LINGER, &zmqLinger/*ms*/, sizeof(zmqLinger));
+ int timeoutMS = 10000;
+ zSocket.setsockopt(ZMQ_SNDTIMEO, &timeoutMS, sizeof(timeoutMS));
+
+ zmq::message_t zmsg;
+ zmsg.rebuild(blockHash.size());
+ memcpy(zmsg.data(), blockHash.c_str(), blockHash.length());
+
+ if (!zSocket.send(zmsg))
+ LogPrintf("zmqBlockNotify error: block hex %s\n", blockHash.c_str());
+}
+
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
diff --git a/src/util.h b/src/util.h
index a4aaf29..e2bd6ab 100644
--- a/src/util.h
+++ b/src/util.h
@@ -106,6 +106,7 @@ boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
boost::filesystem::path GetTempPath();
void ShrinkDebugFile();
void runCommand(std::string strCommand);
+void zmqBlockNotify(const std::string &blockHash, const std::string &zmqLocalUri);
inline bool IsSwitchChar(char c)
{
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment