简体   繁体   English

STDIN和传入套接字上的select()

[英]select() on STDIN and Incoming Socket

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. 我正在尝试用C语言编写一个非常基本的聊天客户端,该客户端使用套接字与另一台计算机通信,并且在理解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));
    }
  }
}

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

Thank you guys so much! 非常感谢你们!

 FD_SET(STDIN, &writefds); 

You want to read from STDIN so you should add STDIN to the &readfds and not &writefds . 您要读取STDIN,因此应将STDIN添加到&readfds而不是&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进行写操作,因此您的代码有效地获得了可以对STDIN进行写操作的信息,但随后尝试从STDIN进行读取并挂起,直到实际可以进行读取为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM