C从客户端向服务器提交命令

时间:2015-01-15 20:10:50

标签: c linux sockets unix udp

我有一个在UDP上运行的客户端 - 服务器应用程序(我需要UDP而不是TCP)。 客户端可以向服务器发送消息,它正常工作,反之亦然。 我希望客户端能够将消息作为“_connect game1 10”传递并在服务器上相应地触发一个名为_connect(char * name,int num)的函数。 如何执行此操作来分析每个命令以触发哪个命令?序列化是一种解决方案,以及如何实现它。

1 个答案:

答案 0 :(得分: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);
    
  4. 在服务器上 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)
          }