美文网首页程序员iOS Developer
Nanomsg简单使用和集成 IOS版

Nanomsg简单使用和集成 IOS版

作者: Macalk | 来源:发表于2017-08-10 20:09 被阅读218次

    如果考虑到使用nanomsg,说明你对它还是有些了解的。在这里就不在详细的介绍它的功能和优缺点,网上的资料特别多,我们只对iOS开发中的简单使用做一些介绍:
    1、github地址:https://github.com/reqshark/nanomsg.ios (大神所著,默哀、感谢)
    2、集成到项目:

    (1) 打开终端: cd 项目根文件
    (2)输入以下命令 ,等待结束

    git clone https://github.com/reqshark/nanomsg.ios && rm nanomsg.ios/README.md
    

    (3)打开项目,右键根目录选择->add files to project->选择nanomsg.ios
    (4)导入头文件到ViewController,宏定义服务器地址

    #import <stdio.h>
    #import <string.h>
    #import "nn.h"
    #import "tcp.h"
    #import "pipeline.h"
    #import "sleep.h"
    #import "pubsub.h"
    #import "req.h"
    #define SOCKET_ADDRESS "tcp://192.168.1.42:5001"
    

    (5)在viewDidLoad里加载方法

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
    /*****S1开启的是服务端,由于项目中没有需求所以没有加入,有兴趣的可以自己研究一下,这里只用到  S2开启客户端*****/
        /* set up some pub sub sockets */
    
        int s2 = nn_socket (AF_SP, NN_SUB);//开启接受模式
        //int s2 = nn_socket (AF_SP, NN_REQ);-->这是发送模式
        
        //subscriber needs to be switched on with a string filter, "" for all msgs
    (在""里填入字符串用来过滤,不填为接受全部。著:我在测试中,不管填入什么都能接收到所有数据,无法过滤,最后自己通过字符串对比,本地实现筛选)
        int r = nn_setsockopt (s2, NN_SUB, NN_SUB_SUBSCRIBE, "", 0);
        if(r > -1){        printf ("subscriber socket set\n");
        } else {
            printf ("error setting subscription socket: %d\n", r);
            // return 1;
        }
        
        /* 链接服务器 */
        nn_connect (s2, SOCKET_ADDRESS);
        nn_sleep (10);
        
        /* 发送数据 */
        char *msg = "DATE:SSSS";
        nn_send (s2, msg, strlen(msg), 0);
        
        /* recv and allocate message to the address of a buffer */
        char *buf = NULL;
        int sz = nn_recv (s2, &buf, NN_MSG, 0);
        buf[sz] = '\0';
        
      /* 输出为接受到的数据 */
        printf("cool: %s\n",buf);
        
        /* free that allocation */
        nn_freemsg (buf);       
    }
    

    (6)注意事项:作者有提示,如遇以下问题

    警告.png

    需要修改以下事项为NO!

    解决.png

    相关文章

      网友评论

        本文标题:Nanomsg简单使用和集成 IOS版

        本文链接:https://www.haomeiwen.com/subject/jyhkrxtx.html