2015-01-15 58 views
1

我有一個運行在UDP上的客戶端 - 服務器應用程序(我需要它UDP不是tcp)。 客戶端可以發送消息到服務器,它的工作正常,反之亦然。 我希望客戶端能夠以「_connect game1 10」的形式傳遞消息,並相應地在服務器上觸發一個名爲_connect(char * name,int num)的函數。 這怎麼可以執行來分析每個命令來觸發什麼命令?並且序列化是一個解決方案以及如何實現它。C從客戶端向服務器提交命令

+0

這聽起來像你想設計一個RPC系統,但不確定從哪裏開始。您可以使用現有的RPC系統,也可以嘗試構建自己的系統,但實際上,這個問題對於堆棧溢出來說有點太廣泛。 –

+0

我知道如何使用rpcgen並設計它的結構。我需要的只是知道如何手動。這是一個大學項目,我需要一點幫助才能夠從服務器調用這個函數並執行它的操作。 – f0unix

+0

那麼你應該和你的教授談談。這對Stack Overflow來說不是一個好問題。 –

回答

1

你可以做以下的東西線步驟 1.創建一個消息結構

typedef struct info 
    { 
     char clientReq[MAX_LENGTH]; 
     char sub[MAX_LENGTH]; 
     u_int32_t value; 
     u_int16_t end; //Set for the packet which closes the connection 

    }messageInfo; 

客戶端

  1. 創建套接字和本地綁定//並連接到服務器套接字(可選)

    fd = socket(family, SOCK_DGRAM, 0); 
    //handle error 
    struct sockaddr_in   peerV4; 
    struct sockaddr_in   clientV4; 
    rc = bind(fd,(struct sockaddr *) &clientV4, 
             sizeof clientV4); 
    //error handling 
    
  2. 發送數據包數據到服務器。

    //update peer(server) socket info here 
        peerV4.sin_family = AF_INET; 
        peerV4.sin_port = htons(serverPort); 
        peerV4.sin_addr.s_addr = "x.x.x.x"; 
        uint8_t *tBuf = (uint8_t *)malloc(sizeof (info)); //memset to zero 
        info *pHeader = (info *)tBuf; 
        pHeader->value = htonl(10); //local value to send 
        pHeader->end = htons(0); 
        pHeader->clientReq = "connect"; 
        pheader->sub = "game1"; 
        sendto(serverSock, tBuf, sizeof(info),0 
               ,(struct sockaddr *) &peerV4, 
               sizeof(peerV4)); 
    
  3. 發送最後一個數據包並關閉本地套接字。

    pHeader->end = htons(1); // so the server closes the socket 
        //send packet 
        close(fd); 
    

在服務器 1.創建一個UDP套接字綁定到本地地址等待客戶端發送的數據,並使用recvfrom,

 fd = socket(family, SOCK_DGRAM, 0); 
     //bind socket 
     uint8_t *recvBuf = (uint8_t *)malloc(sizeof(info)); 
     info *pheader = (info *)recvBuf; 
     int currLen = recvfrom(fd, recvBuf, 
        mBufLen),0,(struct sockaddr *)&peerV4, 
        &sockaddrLen); 
     //error handling 
     if(currLen > 0) 
     { 
      if(htons(pheader->end) == 1) 
      //close socket 
      char *localSub = pheader->sub; 
      char *localRecv = pheader->clientReq; 
      //do something with the values on the server like 
      if (strcasecmp(localRecv,"connect")  == 0) //pseudo 
       connect(sub,pheader->value) 
     } 
相關問題