你好,我试图自己进行C Socket编程,最近我陷入了这个问题,我创建了运行良好的服务器,但是我相信客户端有问题,因为在第一次询问服务器之后第二次不再起作用了无论输入什么数字,他都陷入无限循环。基本上,我的应用程序是这样工作的,客户端连接到服务器,他收到一个菜单以获取图片和文本文件(尚未实现),客户端选择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);
答案 0 :(得分:1)
我认为客户端存在一些问题,因为在第一次对服务器进行第二次询问之后,它不再起作用了……
这是服务器,有问题 ,即在仍建立连接的情况下重复调用accept
。解决方案是在服务器菜单的发送和对客户端选择的响应(例如e)周围建立一个内部循环。 G。通过更改
send(new_fd,msg,sizeof(msg),0);
到
while (send(new_fd, msg, sizeof msg, 0) > 0)
(没有;
)。