我正在尝试在c中编写一个简单的服务器来玩双人游戏。它检查传入的连接,如果没有player1,它会保存player1的文件描述符(稍后用于发送和接收),如果没有player2,它也会这样做。我有这个循环设置,我从Here修改。我的问题是,我想从一个接收,并发送给另一个,但似乎我的作业无效。当我尝试发送到player2时,它失败或者它发送垃圾。有时,发送到player1发送回服务器(?)。我是否正确使用选择并正确循环文件描述符?任何反馈都将不胜感激。
// add the listener to the master set
FD_SET(listener, &master);
// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one
// main loop
while (1) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
error("select");
}
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
//This indicates that someone is trying to do something
if (FD_ISSET(i, &read_fds)) {
if (i == listener) {
addrlen = sizeof remoteaddr;
newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen);
if (newfd == -1) {
error("accept");
} else {
FD_SET(newfd, &master);
if (newfd > fdmax) {
fdmax = newfd;
}
/* If we have the maximum number of players, we tell if that it's busy */
if (players >= 2) {
toobusy(fdmax); close(fdmax); FD_CLR(fdmax, &master);
} else {
//Problem here?
if (player1_fd == -1) {
player1_fd = newfd;
}
if ((player1_fd != -1) && (player2_fd == -1)) {
player2_fd = newfd;
}
players++;
if (players == 2) {
sendhandles(); //says two players exist
}
}
}
} else {
//Possible problems here
if (i == player1_fd || i == player2_fd) {
receive(i); //Processes the messages
}
}
}
}
}
答案 0 :(得分:0)
toobusy
部分应该使用newfd,而不是fdmax。否则,此代码中没有容易发现的错误。
你的评论“有时,发送给player1发送回服务器(?)”让我觉得player1_fd和player2_fd可能未初始化或者可能初始化为0而不是-1。您应该仔细检查在循环之前将它们设置为-1。
还有一些注意事项:
最后,我建议使用库来进行事件处理,例如libevent或libev。