请原谅我是个小白,可能问题比较幼稚。
今天,在进行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。
在各种尝试后未能找到解决办法。
什么是Socket Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序。要学Internet上的TCP/IP网络编程,必须理解Socket接口。 Socket接口设计者......
答案就在这里:linux socket 通信编程
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。
请问是tcp/ip?listen,accept哪里去了?
请参考linux socket 客户端和服务器通信:
http://blog.csdn.net/feng1790291543/article/details/52091225