服务器与多个客户端 - 与选择写作() [英] Server with multiple clients - writing with select()

查看:124
本文介绍了服务器与多个客户端 - 与选择写作()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写在同一时间处理多个客户端的服务器。显然,我应该使用选择。我发现很多教程,但他们没有处理写作。

I'm trying to write a server that handles multiple clients at a time. Apparently I'm supposed to use select. I've found numerous tutorials but none of them handle writing.

我得到我应该如何读取数据,但什么是来处理我的'循环'写回客户端的..适当的方式?

I get how I'm supposed to read data in, but what's the.. appropriate way to handle writing back to the clients in my 'loop'?

先谢谢了。

推荐答案

如果您有要发送到一个特定的套接字的数据,那么你就需要选择()返回时,有在该套接字输出缓冲区的可用空间。顺便告诉选择()做类似于使用select()只是为了读 - 除非你也做FD_SET第二FD_SET对象

If you have data that you want to send to a particular socket, then you need select() to return when there is space available in that socket's output-buffer. The way to tell select() to do that is similar to using select() just for read -- except that also you do the FD_SET on the second fd_set object.

int socks[10] = {... some client sockets...}

while(1)
{
   fd_set readSet, writeSet;

   FD_ZERO(&readSet);
   FD_ZERO(&writeSet);

   int maxSock = -1;
   for (int i=0; i<10; i++)
   {
      FD_SET(socks[i], &readSet);
      if (socks[i] > maxSock) maxSock = socks[i];

      if (IHaveDataToSendToThisSocket(i))  // implement this function as appropriate to your program
      {
         FD_SET(socks[i], &writeSet);
         if (socks[i] > maxSock) maxSock = socks[i];
      }
   }

   int ret = select(maxSock+1, &readSet, &writeSet, NULL, NULL);
   if (ret < 0)
   {
      perror("select() failed");
      break;
   }

   // Do I/O for sockets that are ready
   for (int i=0; i<10; i++)
   {
      if (FD_ISSET(socks[i], &readSet))
      {
         // there is data to read on this socket, so call recv() on it
      }

      if (FD_ISSET(socks[i], &writeSet))
      {
         // this socket has space available to write data to, so call send() on it
      }
   }
}

这篇关于服务器与多个客户端 - 与选择写作()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆