2013-10-30 81 views
0

我正在製作一個程序來通過網絡發送和接收消息,我現在已經設置了重複消息50次,但是我希望它將每條消息延遲一秒鐘。有沒有一種方法可以使用select做到這一點?如果不是,我該怎麼辦呢?我該如何延遲一秒鐘? UDP客戶端

謝謝。

下面是我的客戶

void 
client (char * servername) { 
    ssize_t  bytes; 
    int   skt; 
    char  buff[BUF_SIZE]; 
    int i; 

    do{ 
    skt = createsocket (servername, PORT); 

    bytes = (ssize_t) sprintf (buff, "Hello %s, sequence number:", servername); 

    if (write (skt, buff, bytes) < bytes) { 
     fprintf (stderr, "WARNING: write didn't accept complete message\n"); 
    } 

    memset (buff, 0, BUF_SIZE); 
    bytes = read (skt, buff, BUF_SIZE); 
    if (bytes < 0) { 
     perror ("read()"); 
     exit (1); 
    } 

    printf ("Server echoed the following: %s\n", buff); 
    i++; 
    }while(i < 50); 
} 

附:代碼我也會嘗試使用長類型在那裏添加一個序列號,我將如何去做這件事?

+1

難道你不能簡單地添加* sleep *(http://linux.die.net/man/3/sleep)或* nanosleep *(http://linux.die .net/man/2/nanosleep)在你的循環結束?這些是針對Linux的,但我相信所有的操作系​​統都應該有相同的功能。 – KBart

+0

OT:「*」警告:寫入不接受完整消息\ n *「爲什麼不循環'write()'發送剩下的內容,直到所有內容都被髮送完畢? – alk

回答

1

這應該是相當接近你想要的。 (未測試)

void client (char * servername) 
{ 
    ssize_t bytes; 
    int skt; 
    char buff[BUF_SIZE]; 
    int i = 0; 
    long seqNum = 0; 

    skt = createsocket (servername, PORT); 

    do 
    { 
     memset (buff, 0, BUF_SIZE); 

     struct timeval t = {1, 0}; 

     select(0, NULL, NULL, NULL, &t); 

     bytes = (ssize_t) sprintf (buff, "Hello %s, sequence number: %ld", servername, seqNum++); 

     if (write (skt, buff, bytes) < bytes) 
     { 
      fprintf (stderr, "WARNING: write didn't accept complete message\n"); 
     } 

     memset (buff, 0, BUF_SIZE); 

     bytes = read (skt, buff, BUF_SIZE); 

     if (bytes < 0) 
     { 
      perror ("read()"); 
      exit (1); 
     } 

     printf ("Server echoed the following: %s\n", buff); 
     i++; 
    } 
    while (i < 50); 
} 
+0

完美,謝謝! – JmJ