【发布时间】:2016-09-11 03:23:03
【问题描述】:
我正在编写与服务器通信、发送和接收数据的客户端代码。 我正在使用 select 函数来监视两个文件描述符 - 0 作为 stdin fd 和 4(socket_dect) 作为套接字 fd。 主要思想是找到 fd 的 whitch 目前处于活动状态,如果 STDING 处于活动状态,则将读取它并将数据发送到服务器,如果套接字 fd 处于活动状态,则将接收数据并打印它。 我不知道为什么,但是当我运行这个客户端时会发生一些事情。 这是我的代码:
// 聊天客户端 // 由 omri 编写
#include <stdio.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <arpa/inet.h> //inet_addr
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#define PORT 9034 // defined port like the server
#define STDIN 0
void main()
{
struct timeval tv; // time values for select function
int activity = 0 ;
int ready; // contains the result of the select function
char buf[256];
int len = strlen(buf);
int byte_sent,i;
int socket_dect; // creating socket descriptor
struct sockaddr_in ServerInfo;
fd_set readfds;
// creating a new socket, its a number represent a file descriptor
// socket args : 1)ip protocol ipv4,second tcp/udp, third is number of protocol used
socket_dect = socket(AF_INET,SOCK_STREAM,0);
if(socket_dect == -1){
perror("error creating socket");
}
// fill the values of the server
ServerInfo.sin_family = AF_INET; // ipv4
ServerInfo.sin_port = htons(PORT); // port number
//ServerInfo.sin_addr = 127.0.0.1;
inet_pton(AF_INET, "127.0.0.1", &ServerInfo.sin_addr);//insert the ip to the sin addr
//fill the values of the time for the select function
tv.tv_sec = 5; // 5 sec
tv.tv_usec = 0; // 0 mili sec
FD_ZERO(&readfds); // clear the socket set
for(i = 0; i<= socket_dect; i++){
FD_SET(i,&readfds);// set the sockets
}
// making the connection to the server
//ServerInfo.sin_addr.s_addr = inet_addr("127.0.0.1"); // another way to put ip addr
connect(socket_dect,(struct sockaddr *)&ServerInfo,sizeof(ServerInfo)); // connected to the server
printf("after connect");
while(1){
ready = select(socket_dect,&readfds,NULL,NULL,&tv);
printf("%d is ready",ready);
if(ready < 0){
perror("select error");
printf("select error");
}
// reading from STDIN to buff
else if(ready == STDIN_FILENO){
if(fread(buf,256,1,&readfds) < 0){
printf("read error");
perror("read error");
}
if(send(socket_dect,buf,len,NULL) < 0){
perror("send connection");
printf("send error");
}//end if send
}//end elseif STDIN
else if(ready == socket_dect){
if(recv(socket_dect,buf,len,0) < 0 ){
printf("recv error");
}
printf("data recived is :%s",buf);
}//end elseif
else{
printf("none is ready");
}
}//end while
}//end main
【问题讨论】:
-
来自select man page:“nfds 是三组中编号最高的文件描述符,加 1”。
-
if(ready == STDIN_FILENO)这不是检查哪个文件描述符准备就绪的正确方法。再次参考手册页:“退出时,集合被修改以指示哪些文件描述符实际更改了状态。” -
因为
select修改了传递给它的 fd 集,所以 fd 集,在本例中为readfds,需要为循环的每次迭代重新设置。此外,该集合应该只包含STDIN_FILENO和socket_dect,而不是这些值之间的所有文件描述符。