我正在制作一个通过网络发送和接收消息的程序,我目前已将其设置为重复该消息50次,但我希望将每条消息延迟一秒钟。有没有办法可以使用select来做到这一点?如果没有,我还能怎么办?
感谢。
这是我客户的代码
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);
}
P.S。我还要尝试使用long类型在那里添加一个序列号,我该怎么做呢?
答案 0 :(得分: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);
}