gpt4 book ai didi

客户端不会多次发送数据

转载 作者:行者123 更新时间:2023-11-30 19:01:33 26 4
gpt4 key购买 nike

您好,我正在尝试为自己学习 C 套接字编程,最近我陷入了这个问题,我创建了服务器,它运行良好,但我相信客户端有一些问题,因为在第一次询问服务器后第二次不再工作,就像无论我输入什么数字,他都会陷入无限循环。基本上我的应用程序是这样工作的,客户端连接到服务器,他收到一个菜单来获取图片和文本文件(尚未实现),客户端选择1个选项,服务器响应等等,直到选择退出选项。

    /* This is accept loop from server */
while(1)
{
sin_size = sizeof(struct sockaddr_in);

if((new_fd = accept/* expression */(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
perror("Server-accept() error");
continue;
}


printf("Server: Got connection from %s\n", inet_ntoa(their_addr.sin_addr));

//Server sends this
char msg[100] ="\nWelcome\n1.Get picture.\n2.Get text file.\n3.Quit\n";
send(new_fd,msg,sizeof(msg),0);

if((recv(new_fd,buf,12,0)) == -1)
{
printf("Didn't receive the data from client\n");
}else
{
printf("I got this from client: %c\n",buf[0]);
char *customMsg;
switch (buf[0]) {
case 49:
customMsg ="Picture sent.";
send(new_fd,customMsg,50,0);
break;
case 50:
customMsg ="Text file sent.";
send(new_fd,customMsg,50,0);
break;
case 51:
customMsg ="Goodbye.";
send(new_fd,customMsg,50,0);
close(new_fd);
printf("Server-new socket, new_fd closed successfully...\n");
break;
}
}

}

/* This is the client from connect phase */

if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect()");
exit(1);
}
int endTransmission = 0;

if((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
{
perror("recv() error");
exit(1);
}

buf[numbytes] = '\0';
printf("Response from server: %s", buf);
do
{
char *valToSend;
printf("Enter your option: ");
scanf("%s",valToSend );
send(sockfd,valToSend,1,0);

recv(sockfd,buf,sizeof(buf),0);


printf("\nThis is what I got back from server:\n%s\n", buf);

if(*valToSend == 3)
endTransmission = 1;
}while(endTransmission != 1);

printf("\nClient-Closing sockfd\n");
close(sockfd);

最佳答案

I believe client has some problem because after first interrogation to server second time is not working anymore …

这是服务器有一些问题,即在连接仍然建立的情况下重复调用accept。解决方案是围绕服务器菜单的发送和对客户端选择的响应设置一个内部循环,例如。 G。通过改变

        send(new_fd,msg,sizeof(msg),0);

        while (send(new_fd, msg, sizeof msg, 0) > 0)

(没有)。

关于客户端不会多次发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com