我想编写一个多客户端套接字程序,
但是在接受阶段我得到了错误的文件描述符。
如何更正我的代码?谢谢!
这是我的代码
http://codepad.org/q0N1jTgz
谢谢!
这是我的部分代码!
while(1)
{
struct sockaddr_in client_addr;
int addrlen = sizeof(client_addr);
/*Accept*/
if(clientfd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&addrlen) < 0)
{
perror("Accpet Error");
close(sockfd);
exit(-1);
}
/*Fork process*/
if(child = fork() < 0)
{
perror("Fork Error");
close(sockfd);
exit(-1);
}
else if(child == 0)
{
int my_client = clientfd;
close(sockfd);
send(my_client, welcome, sizeof(welcome), 0);
while ((res = recv(my_client, buffer1, sizeof(buffer1), 0)) > 0)
{
string command(buffer1);
cout << "receive from client:" << command << ", " << res << " bytes\n";
memset(buffer1, '\0', sizeof(buffer1));
}
}
close(clientfd);
}