我正在尝试实现一个客户端-服务器程序。但是,虽然服务器程序运行良好,但客户端程序退出并显示错误::recv:传输端点未连接。它让我困惑了很长一段时间。一些帮助将不胜感激!这是服务器程序::
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
int main()
{
int sockid,newsockid,pid;
struct sockaddr_in myaddr,clientaddr;
socklen_t x;
x=sizeof(clientaddr);
char msg[20];
sockid=socket(AF_INET,SOCK_STREAM,0);
if(sockid == -1)
perror("SOCKET");
memset(&myaddr,0,sizeof(myaddr));
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(8888);
myaddr.sin_addr.s_addr=inet_addr(INADDR_ANY);
if(bind(sockid,(const struct sockaddr *)&myaddr,sizeof(myaddr)) == -1)
perror("bind");
listen(sockid,5);
newsockid=accept(sockid,(struct sockaddr *)&clientaddr,&x);
if(newsockid == -1)
perror("accept");
printf("NEW CLIENT ADDR:: %s",ntohs(clientaddr.sin_addr.s_addr));
pid=fork();
while(1)
{
if(pid == 0)
{
memset(msg,'\0',20);
if(recv(newsockid,msg,sizeof(msg),0) == -1)
perror("recv");
puts(msg);
if(strcmp(msg,"exit") == 0)
{
close(newsockid);
exit(getpid());
}
}
if(pid!=0)
{
memset(msg,'\0',20);
gets(msg);
if(send(newsockid,msg,sizeof(msg),0) == -1)
perror("send");
if(strcmp(msg,"exit") == 0)
{
close(newsockid);
exit(getpid());
}
}
}
return 0;
}
这也是事物的客户端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
int main()
{
int pid,sockfd;
char msg[20];
struct sockaddr_in myaddr;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd == -1)
perror("socket");
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(8888);
myaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr)) == -1)
perror("connect");
pid=fork();
while(1)
{
if(pid == 0)
{
memset(msg,'\0',20);
if(recv(sockfd,msg,sizeof(msg),0) == -1)
{
perror("recv");
exit(getpid());
}
puts(msg);
if(strcmp(msg,"exit") == 0)
{
close(sockfd);
exit(getpid());
}
}
if(pid!=0)
{
memset(msg,'\0',20);
gets(msg);
if(send(sockfd,msg,sizeof(msg),0) == -1)
perror("send");
if(strcmp(msg,"exit") == 0)
{
close(sockfd);
exit(getpid());
}
}
}
return 0;
}