连续运行服务器套接字

时间:2015-01-07 08:49:37

标签: c sockets

我已经编写了使用TCP套接字在服务器和客户端之间建立连接的代码。我在断开客户端方面遇到了问题。即使当前客户端关闭,我希望服务器端连续运行等待下一个客户端。 我的客户端代码:

int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,c;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
    printf("\n Usage: %s <ip of server> \n",argv[0]);
    return 1;
} 

memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    printf("\n Error : Could not create socket \n");
    return 1;
} 

memset(&serv_addr, '0', sizeof(serv_addr)); 

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(6006); 

if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
    printf("\n inet_pton error occured\n");
    return 1;
} 

if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
   printf("\n Error : Connect Failed \n");
   return 1;
} 
while(1)
{
printf("\n 1 to read \n");
printf("\n 2 to disconnect \n");        
printf("\n 3 to exit \n");
scanf("%d",&c);
    switch(c)
    {
    case 1:
        printf("\n Inside case 1 \n");
        if((n=send(sockfd,&c,sizeof(c),0))>0)
            printf("\n Sent \n");
        n = recv(sockfd, recvBuff, sizeof(recvBuff)-1,0);
        recvBuff[n] = 0;
            if(fputs(recvBuff, stdout) == EOF)
            {
                    printf("\n Error : Fputs error\n");
            }
        break;
    case 2:
        close(sockfd);//to close only client not server 
    case 3:
        close(sockfd);
        exit(1);



    }
}

}

服务器端代码:

int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0,info,n;
struct sockaddr_in serv_addr; 

char sendBuff[1025];
time_t ticks; 
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff)); 

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(6006); 

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 

listen(listenfd, 10); 

while(1)
{
    connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); 
printf("\n Accepted \n");
while(1)
{
    printf("\n Inside while \n");
    if((n=recv(connfd,&info,sizeof(info),0))>0)
    printf("\n received \n");
    switch(info)
    {
    case 1:
            ticks = time(NULL);
            snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
            send(connfd, sendBuff, strlen(sendBuff),0); 
        break;
    }
}
close(connfd);


 }

} 

为我提供解决方案,在服务器运行时断开客户端(服务器等待下一个客户端连接)。即使我在案例2中使用return 0它也不起作用。请帮助我。谢谢你提前

1 个答案:

答案 0 :(得分:0)

else if(n == 0)
{
   printf("client disconnected\n");
   close(connfd);
   break;
}

旁边的服务器程序中添加上述代码
if((n=recv(connfd,&info,sizeof(info),0))>0)
    printf("\n received \n");

问题是当您的客户端断开连接时,您需要发送一些api来关闭客户端连接。

如果客户端已正常断开连接,则上面的行将用于自动关闭该客户端。

然后在snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));中发出警告。