req/rep 模式显然就是类似http的应答模式。在某些基于短连接的进程间通讯方式上可以很方便的使用。下面我们举个例子:

服务端:demo


#ifndef NANOMSGUTIL_H
#define NANOMSGUTIL_H#include "messageDispatch.h"
#include "thread/nthread.h"class NanomsgServer : public QThread
{public:NanomsgServer(const QString url = "tcp://127.0.0.1:5555");int NanoServer();virtual void run() override final;int process();void stop();private:QString m_url;bool m_stopFlag = false;MessageDispatch m_dispatcher; /// 消息分发处理
};#endif
#include "nanomsgServer.h"
#include <NLog>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>/*Copyright 2016 Garrett D'Amore <garrett@damore.org>Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"),to deal in the Software without restriction, including without limitationthe rights to use, copy, modify, merge, publish, distribute, sublicense,and/or sell copies of the Software, and to permit persons to whomthe Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be includedin all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALLTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSIN THE SOFTWARE."nanomsg" is a trademark of Martin Sustrik
*//*  This program serves as an example for how to write an async RPC service,using the RAW request/reply pattern and nn_poll.  The server receivesmessages and keeps them on a list, replying to them.Our demonstration application layer protocol is simple.  The client sendsa number of milliseconds to wait before responding.  The server just givesback an empty reply after waiting that long.To run this program, start the server as async_demo <url> -sThen connect to it with the client as async_client <url> <msec>.For example:% ./async_demo tcp://127.0.0.1:5555 -s &% ./async_demo tcp://127.0.0.1:5555 323Request took 324 milliseconds.
*/#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#else
#include <sys/time.h>
#endif#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>/*  MAXJOBS is a limit on the on the number of outstanding requests wecan queue.  We will not accept new inbound jobs if we have more thanthis queued.  The reason for this limit is to prevent a bad clientfrom consuming all server resources with new job requests. */#define MAXJOBS 100
#define MAXLENS 10*1024/*  The server keeps a list of work items, sorted by expiration time,so that we can use this to set the timeout to the correct value foruse in poll.  */
struct work {struct work *next;struct nn_msghdr request;uint64_t expire;void *control;
};#ifdef WIN32
int gettimeofday(struct timeval *tp, void *tzp)
{time_t clock;struct tm tm;SYSTEMTIME wtm;GetLocalTime(&wtm);tm.tm_year   = wtm.wYear - 1900;tm.tm_mon   = wtm.wMonth - 1;tm.tm_mday   = wtm.wDay;tm.tm_hour   = wtm.wHour;tm.tm_min   = wtm.wMinute;tm.tm_sec   = wtm.wSecond;tm. tm_isdst  = -1;clock = mktime(&tm);tp->tv_sec = clock;tp->tv_usec = wtm.wMilliseconds * 1000;return (0);
}
#endif/*  Return the UNIX time in milliseconds.  You'll need a workinggettimeofday(), so this won't work on Windows.  */
uint64_t milliseconds (void)
{struct timeval tv;gettimeofday (&tv, NULL);return (((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000));
}NanomsgServer::NanomsgServer(const QString url)
{m_url = url;
}/*  The server runs forever. */
void NanomsgServer::run()
{INFO_PRINT_LINE << "start service thread.";int fd;struct work *worklist = NULL;int npending = 0;/*  Create the socket. */fd = nn_socket(AF_SP, NN_REP);if (fd < 0) {fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));return ;}/*  Bind to the URL.  This will bind to the address and listensynchronously; new clients will be accepted asynchronouslywithout further action from the calling program. */if (nn_bind (fd, m_url.toStdString().data()) < 0) {fprintf (stderr, "nn_bind: %s\n", nn_strerror (nn_errno ()));nn_close (fd);return ;}/*  Main processing loop. */while(!m_stopFlag){void *buf = NULL;int nbytes = nn_recv (fd, &buf, NN_MSG, 0);if (nbytes < 0) {fprintf (stderr, "nn_recv: %s\n",nn_strerror (nn_errno ()));nn_freemsg (buf);continue;}char* request = NULL;request = (char*)malloc(nbytes+1);//memcpy((void*)request,buf,nbytes);strncpy(request,(const char*)buf,nbytes);request[nbytes] = '\0';QByteArray ba = QByteArray(request).trimmed();//INFO_PRINT_LINE << (char*)buf << nbytes;INFO_PRINT_LINE << request << strlen(request);/// message dispatchQJsonDocument loadDoc(QJsonDocument::fromJson(ba));QJsonObject dataObj = loadDoc.object();/// deal messageQString responce = m_dispatcher.deal(QString(request));// responce to clientconst char *d = responce.toUtf8().constData();int sz_d = strlen(d) + 1; // '\0' toonbytes = nn_send (fd, d, sz_d, 0);assert (bytes == sz_d);INFO_PRINT_LINE << "[responce]  " << d << nbytes;free(request);nn_freemsg (buf);}nn_close (fd);return;
}void NanomsgServer::stop()
{INFO_PRINT_LINE << "stop";if (QThread::isRunning()){INFO_PRINT_LINE << "stop";m_stopFlag = true;QThread::quit();QThread::wait();}
}

客户端:demo

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#else
#include <sys/time.h>
#endif#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
#define DEFAULT_URL             "tcp://127.0.0.1:5555"
#define DEFAULT_BUFFER_SIZE     (10*1024)char npi_appId[32] = {0};/*************************  Log Module *******************************/
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000enum {LL_NOTICE     = 1,   //一般输出LL_WARNING    = 2,   //告警输出LL_TRACE  = 3,   //追踪调试LL_DEBUG  = 4,   //软件bugLL_FATAL     = 5     //致命错误
};#define Print_NOTICE(log_fmt,...) \do{ \printf("L(%d)[%s:%d][%s]:  "log_fmt"\n", LL_NOTICE,__FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \}while (0)#define Print_WARN(log_fmt,...) \do{ \printf("L(%d)[%s:%d][%s]:  "log_fmt"\n", LL_WARNING, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \}while (0)#define Print_TRACE(log_fmt,...) \do{ \printf("L(%d)[%s:%d][%s]:  "log_fmt"\n", LL_TRACE,__FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \}while (0)#define Print_DEBUG(log_fmt,...) \do{ \printf("L(%d)[%s:%d][%s]:  "log_fmt"\n", LL_DEBUG, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \}while (0)#define Print_FATAL(log_fmt,...) \do{ \printf("L(%d)[%s:%d][%s]:  "log_fmt"\n",LL_FATAL, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \}while (0)int NanoClientRequest(const char *url , const char* request, long len,char* result);/*************************  nanomsg client  *******************************/
#define MAXJOBS 100
#define MAXLENS 10*1024struct work {struct work *next;struct nn_msghdr request;uint64_t expire;void *control;
};#ifdef WIN32
int gettimeofday(struct timeval *tp, void *tzp)
{time_t clock;struct tm tm;SYSTEMTIME wtm;GetLocalTime(&wtm);tm.tm_year   = wtm.wYear - 1900;tm.tm_mon   = wtm.wMonth - 1;tm.tm_mday   = wtm.wDay;tm.tm_hour   = wtm.wHour;tm.tm_min   = wtm.wMinute;tm.tm_sec   = wtm.wSecond;tm. tm_isdst  = -1;clock = mktime(&tm);tp->tv_sec = clock;tp->tv_usec = wtm.wMilliseconds * 1000;return (0);
}
#endifuint64_t milliseconds (void)
{struct timeval tv;gettimeofday (&tv, NULL);return (((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000));
}/*  The client runs just once, and then returns. */
int NanoClientRequest (const char *url, const char* request, long len, char *result)
{int fd;int rc;fd = nn_socket (AF_SP, NN_REQ);if (fd < 0) {fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));return (-1);}if (nn_connect (fd, url) < 0) {fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));nn_close (fd);return (-1);}if (nn_send (fd, request, len , 0) < 0) {fprintf (stderr, "nn_send: %s\n", nn_strerror (nn_errno ()));nn_close (fd);return (-1);}void* buf = NULL;rc = nn_recv (fd, &buf, NN_MSG , 0);if (rc < 0) {fprintf (stderr, "nn_recv: %s\n", nn_strerror (nn_errno ()));nn_close (fd);return (-1);}Print_TRACE("[recv rep]: %d  %s",rc,buf);memcpy((void*)result,buf,rc);nn_freemsg (buf);nn_shutdown (fd, 0);return 0;
}

【开源之美】nanomsg(2) :req/rep 模式相关推荐

  1. 【zmq】REQ REP 模式

    [c代码(https://github.com/dongyusheng/csdn-code/tree/master/ZeroMQ) zguide 官方有c++ 发布订阅:可以使用信封 发布订阅可以让消 ...

  2. Python+ZeroMQ使用REQ/REP模式快速实现消息收发

    推荐图书: <Python程序设计(第3版)>,(ISBN:978-7-302-55083-9),董付国,清华大学出版社,2020年6月第1次印刷,2021年1月第6次印刷,山东省一流本科 ...

  3. 开源超美css动态背景 可直接引入html文件使用 含注释、可更改

    开源超美css动态背景 可直接引入html文件使用 含注释.可更改 1.背景样式 本背景为动态蜘蛛网背景. 上图: 2.如何在html里面引用,作为html背景 1文件目录 放在同一目录下 2 在in ...

  4. Kotlin-Android开发之开源《新闻APP》基于MVP模式+Retrofit2.0+RxJava1.0+Dagger2框架

    前言:此项目是一个适合刚入门安卓开发的且熟悉Kotlin的练手小项目,基于<Kotlin-Android开发之MVP模式+Retrofit2.0+RxJava1.0+Dagger2框架封装> ...

  5. 开源要自立?华为如何“复制”Google模式

    作者 | 郭芮 回首刚刚过去的五月,注定会给很多技术人留下浓墨重彩的一笔. 2018 年 4 月,曾经占据智能手机全球份额第九.美国第四大智能手机供应商的中兴因为一道"销售禁令", ...

  6. 大开源时代,“仁慈的独裁者”管理模式还走得通吗?

    随着越来越多的企业.团队和个人开发者的加入和支持,开源软件迅速渗透到各行各业.如今的开源管理模式主要可分为三种: 一是由社区主导.该模式具有独立.高效率等特点,"共识"是重要前提. ...

  7. 开源CRM+SaaS云服务的生态模式能否撬动中国管理软件市场?

    国内外知名开源CRM软件 开源软件(英语:open source software,英文缩写:OSS,中文也称:开放源代码软件)是一种源代码可以任意获取的计算机软件,这种软件的版权持有人在软件协议的规 ...

  8. 聚科技精英,享开源之美- 2019 Open Source Summit 主题演讲+项目亮点

    2019年6月24-26日,在上海世博中心,由Linux基金会主办的LinuxCon + ContainerCon + CloudOpen大会(简称LC3)将与CNCF主办的KubeCon + Clo ...

  9. 独立开发者+开源项目,超级个体的价值模式

    CodeJoy 今天这个话题,让我想起了之前介绍过一名 creative developer,懂技术又懂艺术的复合型人才 creative developer 2021.6.28 Bruno Simo ...

  10. php 类似于趣步,完整数据全开源早起打卡项目趣步模式源码

    语言: PHP 数据库: Mysql 价值5888元  全开源早起打卡项目( 深蓝引擎Z )趣步模式    完整数据源码 源码介绍 深蓝引擎"Z"系统是一款基于区块链模式开发的早起 ...

最新文章

  1. leetcode算法题--对链表进行插入排序
  2. RabbitMQ官方中文入门教程(PHP版) 第三部分:发布/订阅(Publish/Subscribe)
  3. 织梦直接写php标签,怎么在自己的php页面中使用dedecms标签
  4. ioc spring 上机案例_Spring的IoC入门案例
  5. LL1分析构造法_【财经职业教育活动周】分析天平的使用——电气环保部
  6. git 查看代码量_学会这三个命令,你就不再是git只会用三板斧的菜鸟了
  7. WCF远程服务器返回了意外响应: (413) Request Entity Too Large问题处理
  8. 90后IT男被准丈母娘拒绝:家境不重要,重要的是…戳中痛处
  9. ZZH:魔兽世界之000:MPQ
  10. H3CIE-----这只是一个过程!
  11. python中xlrd模块的用法_用xlrd模块读取合并单元格(merged cell)
  12. 2021 年年度最佳开源软件!
  13. 江西计算机竞赛有哪些,江西自主招生认可的竞赛有哪些
  14. 企业微信员工能私加客户吗?员工私自联系客户企业是否知道?
  15. DialogFragment以及AlertDialogFragment
  16. linux下的pstack和gstack命令
  17. 叠加定理和戴维宁定理
  18. macOS上使用Openconnect代替Cisco Anyconnect
  19. SDN之NOS概述——云原生
  20. 看图写英语作文关于计算机,看图写一篇英文作文

热门文章

  1. android 生成bks_在Android上实现SSL通信(二)
  2. linux中ftp禁止匿名,linux下禁止root和匿名用户登录ftp
  3. ADB 学习(4):adb shell (上)
  4. Qt 之 QQ系统表情(一)
  5. 200行代码实现推流到直播平台
  6. CVE-2021-1675 Print Spooler漏洞复现远程执行及提权
  7. 自定义形状按钮的实现
  8. 物联网和区块链:挑战与风险
  9. 电子料盘 电容 物料标识识别
  10. 卡尔曼滤波-卡尔曼滤波全篇讲解