STDIN和传入套接字上的select() [英] select() on STDIN and Incoming Socket

查看:119
本文介绍了STDIN和传入套接字上的select()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用C语言编写一个非常基本的聊天客户端,该客户端使用套接字与另一台计算机通信,并且在理解select方面遇到了一些问题.这是相关代码的简短片段.

I'm trying to write a very basic chat client in C which communicates with another machine using sockets, and I'm having some issues with understanding select. Here's a quick snippet of the relevant code.

while(1)
  {
    FD_ZERO(&readfds);
    FD_ZERO(&writefds);

    FD_SET(STDIN, &writefds);
    FD_SET(connectFD, &readfds);

    select(connectFD+1, &readfds, &writefds, NULL, NULL);

    if(FD_ISSET(connectFD, &readfds) != 0)
    {
      char buf[1024];
      memset(buf, 0, sizeof(buf));
      int lastBit;

      lastBit = recv(connectFD, buf, sizeof(buf), 0);
      if (lastBit > 0 && lastBit < 1024)
      {
        buf[lastBit] = '\0';
      }
      else
      {
        close(connectFD);
        break;
      }
      printf("%s\n", buf);
    }

    else if (FD_ISSET(STDIN, &writefds))
    {
      char msg[1024];
      memset(msg, 0, sizeof(msg));
      read(STDIN, msg, sizeof(msg));
    }
  }
}

我要做的是在收到传入消息后立即对其进行处理,并且只有在按ENTER键之后才发送传出消息,但是现在我只在按下ENTER键后才处理传入数据,而不是立即处理.我认为这是因为read是一个阻塞调用,并且当缓冲区中有任何数据时,select都将返回,不仅是当有换行符(read返回时),而且我不知道如何处理它.有什么建议或提示可以引导我走上正确的道路吗?

What I'm looking to do is have incoming messages processed as soon as they arrive, and only have outgoing messages sent after I hit ENTER, but what I have now only processes incoming data after I hit ENTER instead of immediately. I assume it's because read is a blocking call and select is returning when there's ANY data in the buffer, not just when there's a newline (which is when read returns), but I don't know how to process this otherwise. Any advice or tips for leading me down the right path?

非常感谢你们!

推荐答案

FD_SET(STDIN, &writefds);

您要读取STDIN,因此应将STDIN添加到&readfds而不是&writefds.几乎总是可以写入STDIN,因此您的代码有效地获得了可以写入STDIN的信息,然后尝试从STDIN读取并挂起,直到实际读取为止.

You want to read from STDIN so you should add STDIN to the &readfds and not &writefds. Writing to STDIN is almost always possible so your code effectively got the information that writing is possible to STDIN but then attempts to read from STDIN and hangs there until the read actually gets possible.

这篇关于STDIN和传入套接字上的select()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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