当前位置: 技术问答>linux和unix
套接字操作的疑惑
来源: 互联网 发布时间:2016-06-18
本文导语: 套接字创建之后,并没有连接,我用select测试该套接字的可读写状态,结果是可读可写,我没弄懂为什么会是这样哦,我用的是 centOS 内核是2.6.9的,,,,下面红色的几行是我添加的测试代码,希望有人帮忙解答一...
套接字创建之后,并没有连接,我用select测试该套接字的可读写状态,结果是可读可写,我没弄懂为什么会是这样哦,我用的是 centOS 内核是2.6.9的,,,,下面红色的几行是我添加的测试代码,希望有人帮忙解答一下。
#include
#include
#include
#include
#include
char *hostName = "127.0.0.1";
int port = 8030;
void main(int argc,char **argv)
{
char buf[8192];
char msg[256];
int sc;
struct sockaddr_in pin;
struct hostent *srvHostName;
char *str = "A default test string";
fd_set rset, wset;
if(argch_addr))->s_addr;
pin.sin_port = htons(port);
sc = socket(AF_INET,SOCK_STREAM,0);
if(sc==-1){
perror("Error opening socketn");
exit(1);
}
/////如下几行是我添加的测试代码,,,,运行的结果令人很不解。。。。。。。。。
FD_ZERO(&wset);
FD_SET(sc,&wset);
rset = wset;
printf("select ret=%dn",select(sc+1,&rset,&wset,0,0));
if(FD_ISSET(sc,&rset)) printf("readablen");
if(FD_ISSET(sc,&wset)) printf("writeablen");
if(connect(sc,(struct sockaddr *)&pin,sizeof(pin))==-1){
perror("Error connecting to servern");
exit(1);
}
FD_ZERO(&rset);
FD_SET(sc,&rset);
while(1){
select(sc+1,&rset,0,0,0);
if(FD_ISSET(sc,&rset)){
if(recv(sc,buf,8192,0)==0){
printf("socket is closedn");
FD_CLR(sc,&rset);
exit(1);
}
}
printf("Sending message %s to server...n",str);
if(send(sc,str,strlen(str),0)==-1){
perror("Error in sendn");
exit(1);
}
printf("..sent message.. wait for response...n");
if(recv(sc,buf,8192,0)==-1){
perror("Error in receiving response from servern");
exit(1);
}
printf("nResponse from server:nn%sn",buf);
}
close(sc);
}
#include
#include
#include
#include
#include
char *hostName = "127.0.0.1";
int port = 8030;
void main(int argc,char **argv)
{
char buf[8192];
char msg[256];
int sc;
struct sockaddr_in pin;
struct hostent *srvHostName;
char *str = "A default test string";
fd_set rset, wset;
if(argch_addr))->s_addr;
pin.sin_port = htons(port);
sc = socket(AF_INET,SOCK_STREAM,0);
if(sc==-1){
perror("Error opening socketn");
exit(1);
}
/////如下几行是我添加的测试代码,,,,运行的结果令人很不解。。。。。。。。。
FD_ZERO(&wset);
FD_SET(sc,&wset);
rset = wset;
printf("select ret=%dn",select(sc+1,&rset,&wset,0,0));
if(FD_ISSET(sc,&rset)) printf("readablen");
if(FD_ISSET(sc,&wset)) printf("writeablen");
if(connect(sc,(struct sockaddr *)&pin,sizeof(pin))==-1){
perror("Error connecting to servern");
exit(1);
}
FD_ZERO(&rset);
FD_SET(sc,&rset);
while(1){
select(sc+1,&rset,0,0,0);
if(FD_ISSET(sc,&rset)){
if(recv(sc,buf,8192,0)==0){
printf("socket is closedn");
FD_CLR(sc,&rset);
exit(1);
}
}
printf("Sending message %s to server...n",str);
if(send(sc,str,strlen(str),0)==-1){
perror("Error in sendn");
exit(1);
}
printf("..sent message.. wait for response...n");
if(recv(sc,buf,8192,0)==-1){
perror("Error in receiving response from servern");
exit(1);
}
printf("nResponse from server:nn%sn",buf);
}
close(sc);
}
|
select描述符同时可读写问题:
http://bbs.chinaunix.net/archiver/?tid-169252.html
http://bbs.chinaunix.net/archiver/?tid-169252.html