Socket通信疑问
今天,在进行socket通信时,发现一个问题,尝试许久后,问能找到答案。
程序功能:
使用socket通信编写服务器与客户端之间的循环应答,直到客户端发送"bye",服务器发送命令关闭客户端,并且服务器关闭。
具体问题描述:
服务器程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/un.h>
int main(void){
int socketfd = socket(AF_LOCAL,SOCK_DGRAM,0);
if ( socketfd == -1 ){
perror("socket");
exit(-1);
}
struct sockaddr_un add;
add.sun_family = AF_UNIX ;
strcpy(add.sun_path,"./sigcom");
//unlink("./sigcom");
int res = bind(socketfd,(struct sockaddr *)&add,sizeof(add));
if( res == -1){
perror("bind");
exit(-1);
}
// res = connect(socketfd,(struct sockaddr *)&add,sizeof(add));
// if( res == -1){
// perror("bind");
// exit(-1);
// }
char buf[20];
while(1){
read(socketfd,buf,sizeof(buf));
printf("%s\n",buf);
if (!strcmp(buf,"bye")){
write(socketfd,"goodbye",sizeof("goodbye"));
printf("GoodBye!\n");
break;
}else{
int d = write(socketfd,"Recived!",sizeof("Recived!"));
if (d == -1){
perror("write");
}
printf("Send!\n");
}
}
close(socketfd);
return 0;
}
客户端程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/un.h>
int main(void){
int socketfd = socket(AF_LOCAL,SOCK_DGRAM,0);
if ( socketfd == -1 ){
perror("socket");
exit(-1);
}
struct sockaddr_un add;
add.sun_family = AF_UNIX ;
strcpy(add.sun_path,"./sigcom");
int res = connect(socketfd,(struct sockaddr *)&add,sizeof(add));
if( res == -1){
perror("connect");
exit(-1);
}
char buf[20];
while(1){
scanf("%s",buf);
write(socketfd,buf,sizeof(buf));
read(socketfd,buf,sizeof(buf));
printf("%s\n",buf);
if (!strcmp(buf,"goodbye")){
printf("%s\n",buf);
break;
}else{
printf("%s\n",buf);
}
}
printf("退出通信!\n");
close(socketfd);
return 0;
}
其中,在服务器这段程序中:
while(1){
read(socketfd,buf,sizeof(buf));
printf("%s\n",buf);
if (!strcmp(buf,"bye")){
write(socketfd,"goodbye",sizeof("goodbye"));
printf("GoodBye!\n");
break;
}else{
int d = write(socketfd,"Recived!",sizeof("Recived!"));
if (d == -1){
perror("write");
}
printf("Send!\n");
}
}
"write"函数出错:Transport endpoint is not connected。
在各种尝试后未能找到解决办法。