2016年6月7日 星期二

0607 IOS socket 建立範例

範例說明:
這是連接robot的其中一段程式碼
因為socket 會卡住task
 所以需要額外建立 thread
透過     threadcv.notify_one(); 啟動thread


//利用socket 測試是否已經連上線
#include <sys/socket.h>
#include <netinet/tcp.h>   //for TCP_NODELAY
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>       // for gethostbyname()

int checkRobotLinkState()
{
    return robotLink_state;
}
void startRobotLinkFun()
{
    robotLink_state=robotlink_conning;
    threadcv.notify_one(); //啟動thread
   
}

void robotSocketLink()
{
    int sock,ret;
    struct sockaddr_in server;
    struct hostent* entp = NULL;
    log("Construct Client...");
    // Create socket
    if( (sock = socket(PF_INET, SOCK_STREAM, 0))<0 )
    {
        log("socket() failed with error \n");
        robotLink_state= robotlink_ER1;
        return;
    }
    // Disable Nagel's algorithm for lower latency
    int yes = 1;
    if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &yes,
                  sizeof(int)) == -1)
    {
        log("failed to enable TCP_NODELAY - setsockopt failed");
        robotLink_state= robotlink_ER2;
        return;
    }
    // Construct server address
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(6665);
   
    // Get host by name
    entp = gethostbyname("192.168.30.1");
    if (entp == NULL)
    {
        log("gethostbyname() failed with error \n");
        robotLink_state= robotlink_ER3;
        return;
    }
    assert(entp->h_length <= sizeof (server.sin_addr));
    memcpy(&(server.sin_addr), entp->h_addr_list[0], entp->h_length);
   
    // Connect
    ret = connect(sock, (struct sockaddr*)&server, sizeof(server));
    if (ret < 0)
    {
        printf("connect call on [%s:%d] failed! \n", "192.168.30.1", 6665);
        robotLink_state= robotlink_ER4;
        return;
    }
    robotLink_state= robotlink_LinkOK;

}

沒有留言:

張貼留言

cocos2dx-lua 建立滑鼠監聽

重要關鍵字  EVENT_MOUSE_SCROLL addEventListenerWithSceneGraphPriority      if IsPc() then --建立滑鼠監聽         local listener = cc.EventListenerMouse...