Avi*_*mar 1 c++ sockets network-programming
我写了下面的代码,以便创建一个echo服务器(我写入stdout的数据从我的PC移动到服务器并返回到我的PC).在代码中,我在套接字中设置了SO_LINGER选项.因此,当我按下Ctrl+ C导致client.cpp向服务器cpp发送FIN时,client.cpp的close()应等待10秒,以便server.cpp的套接字发送回FIN.
但我发现client.cpp立即完成执行并在Ctrl+ C被按下后退出,即使close()函数没有返回-1,如果另一方在l_linger中提到的时间之前没有发送FIN,它应该有到期(我确定服务器没有发送FIN或它必须已经在tcpdump中列出.)服务器端没有发送FIN,除非我在其终端上按Ctrl+ C.tcpdump直到我按下服务器终端上的Ctrl+ C,如屏幕截图所示:
上面突出显示的行是客户的FIN.
client.cpp:
int main()
{
int clifd;
clifd=socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
sockaddr_in serv;
bzero(&serv, sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(3345);
inet_aton("127.0.0.1", &(serv.sin_addr));
linger lin;
unsigned int y=sizeof(lin);
lin.l_onoff=1;
lin.l_linger=10;
setsockopt(clifd,SOL_SOCKET, SO_LINGER,(void*)(&lin), y);
connect(clifd, (sockaddr*)(&serv), sizeof(serv));
int n,m;
char data[100];
char recvd[100];
for(;;)
{
fgets(data, 100,stdin );
n=strlen(data);
cout<<"You have written "<<n<<endl;
if(n>0)
{
while(n>0)
{
m=write(clifd,data,n);
n=n-m;
}
}
n=read(clifd, recvd, 100);
cout<<"Server echoed back "<<n<<endl;
if(n>0)
{
while(n>0)
{
m=fputs(data,stdout);
cout<<"m is"<<m<<endl;
fflush(stdout);
n=n-m;
}
//cout<<data<<endl;
}
}
int z=close(clifd);
if(z==-1)
cout<<"close returned -1 "<<endl; ***//this doesn't get printed***
}
Run Code Online (Sandbox Code Playgroud)
server.cpp:
void reflect(int x)
{
int n;
int m;
char data[100];
cout<<"Entered reflect function"<<endl;
for(;;)
{
n=read(x,data, 100);
cout<<"Client sent "<<n<<endl;
if(n>0)
{
while(n>0)
{
m=write(x,data,n);
n=n-m;
}
cout<<"Successfully echoed back to client"<<endl;
}
}//end of for loop
}
int main()
{
sockaddr_in serv;
bzero(&serv, sizeof(serv));
serv.sin_family=AF_INET;
serv.sin_port=htons(3345);
inet_aton("127.0.0.1", &(serv.sin_addr));
int servfd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int x;
x=bind(servfd, (sockaddr*)(&serv), sizeof(serv));
cout<<"Bind returned"<<x<<endl; //this displays x as 0
listen(servfd, 5);
sockaddr cli;
int connfd;
pid_t id=-1;
socklen_t siz=sizeof(cli);
for(;;)
{
if((connfd=accept(servfd, &cli, &siz))>=0)
id=fork();
if(id==0)
reflect(connfd);
else
continue;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么客户关闭()不等待?
为什么客户关闭()不等待?
你没有打电话给close()
你的客户.for
紧接在您close()
呼叫之前的循环永远不会退出,因此close()
永远不会发生.
键入CTRL- C在您的控制台中导致程序立即退出,而不执行任何其余操作.
既然close()
永远不会被调用,你问的其余部分(应该close()
等待?我应该使用closesocket()
?等)是没有实际意义的.
如果您确实希望能够退出for(;;)
循环,请尝试以下方法:
for(;;)
{
if(fgets(data, 100,stdin ) == NULL)
break;
... rest of loop goes here ...
Run Code Online (Sandbox Code Playgroud)
然后,当您运行客户端程序时,不要使用CTRL- C,而是键入CTRL- D作为行中唯一的字符来终止它.
归档时间: |
|
查看次数: |
5852 次 |
最近记录: |