我对Linux/socket编程相当陌生。我使用select
来检查服务器程序中的连接(它最终将成为聊天室服务器)。我正在使用telnet来测试它,并且发生了一些奇怪的事情。当我第一次运行telnet (telnet localhost 5794)时,select
返回1并将新连接添加到我的主文件描述符列表中。一切都很好。
但是我试着在telnet中输入东西,什么也没发生。Select返回0,除非打开一个新的telnet会话。
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 newConnectionn");
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,所以我可以看到它何时进入函数。
问题在这里
int main(int argc, char *argv[])
{
int maxFD = ...;
...
newConnection(..., maxFD, ...);
...
}
void newConnection(..., int maxFD, ...)
{
...
if (newFD > maxFD)
maxFD = newFD;
...
}
注意,有两个名为maxFD
的变量:一个在main
函数中,另一个在newConnection
函数中。改变一个并不会改变另一个。建议:使用全局变量。(原因:整个应用程序只有一个,许多函数需要访问它。)
这是一个非常非常基本的错误。如果您没有拍着额头说:"哦,这很明显",那么您可能希望回去复习一下编程入门书籍。