1

我对 Linux/socket 编程相当陌生。我select用来检查我的服务器程序中的连接(它最终将是一个聊天室服务器)。我正在使用 telnet 对其进行测试,但发生了一些奇怪的事情。当我第一次运行 telnet (telnet localhost 5794) 时,select返回 1 并将新连接添加到我的主文件描述符列表中。一切看起来都很好。

但后来我尝试在 telnet 中输入内容,但没有任何反应。除非我打开一个新的 telnet 会话,否则选择返回 0。

只是select为了寻找新的联系?我想我也可以用它来检查输入。下面是我的代码的副本(目前有点乱,因为过去几个小时我一直在疯狂地弄乱它。对不起)

#include "chatpacket.cpp"
#include "serverFunctions.cpp"

#define SERVER_PORT 5794
#define MAX_PENDING 10

int main () {
  fd_set connections;
  fd_set waitingConnections;
  user *clients = new user[50];
  int serverSocket = ServerSetup (SERVER_PORT, MAX_PENDING);
  int maxFD = serverSocket;
  int ConnectionCount;

  struct timeval tv;

  FD_ZERO(&connections);
  FD_SET(0, &connections);
  FD_SET(serverSocket, &connections);

  tv.tv_sec = 1;
  tv.tv_usec = 100;

  bool shutdown = false;
  bool tmpflag = true;
  while(!shutdown) { 

    if (tmpflag == true){printf("in the loop!\n");tmpflag=false;}
    waitingConnections = connections;

    ConnectionCount = select((maxFD+1), &waitingConnections, NULL, NULL, &tv);

    if (ConnectionCount == -1) {
        ///HANDLE ERROR!!!!!!
        printf("Connection Error!");
    }
    else if (ConnectionCount > 0) {
      if (FD_ISSET(serverSocket, &waitingConnections)){
           newConnection(serverSocket, connections, maxFD, clients); //this works fine
      }
      else {
           checkConnections(clients, waitingConnections, maxFD); //the code never gets here
      }
    }

    //check keyboard
    shutdown = checkKeyboard();

  }
}

编辑:这是 newConnection 的代码:

bool newConnection(int serverSocket, fd_set& ConnectionList, int maxFD, user* userGroup){
    printf("in newConnection\n");
    struct sockaddr_storage remoteaddr;

    socklen_t addrlen = sizeof remoteaddr;

    int newFD = accept(serverSocket,(struct sockaddr *)&remoteaddr,&addrlen);
    FD_SET(newFD, &ConnectionList);

    if (newFD > maxFD)
        maxFD = newFD;

    printf("We have a new connection!!! (newConnetcion)\n");

    bool userAdded = false;
    for (int i = 0; i < 50; i++){
      if (userGroup[i].active == false){
            userGroup[i].socket = newFD;
            userGroup[i].active = true;
            userAdded = true;
                        printf("User added in the %ith position of the array.(socket number %i)\n",i,newFD);
            break;
      }
    }
    if (!userAdded)
        printf("new user was not added! (newConnetcion)\n");
}

checkConnections 函数在它的开头有一个 printf ,所以我可以在它进入函数时看到它。它从不打印。

4

1 回答 1

1

这是问题所在。

int main(int argc, char *argv[])
{
    int maxFD = ...;
    ...
    newConnection(..., maxFD, ...);
    ...
}

void newConnection(..., int maxFD, ...)
{
    ...
    if (newFD > maxFD)
        maxFD = newFD;
    ...
}

请注意,有两个名为 的变量maxFD:一个在main函数中,一个在newConnection函数中。改变一个不会改变另一个。建议:改用全局变量。(原因:整个应用只有一个,很多功能需要访问。)

这是一个非常非常基本的错误。如果您没有拍拍额头说“哦,这很明显”,那么您可能希望返回并查看编程入门书籍。

于 2011-10-28T05:06:04.697 回答