我正在尝试在客户端和服务器之间建立套接字连接,其中服务器创建套接字并从中读取,客户端将数据写入服务器。这是我的代码:
//server.c
/* a server in the unix domain.*/
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/un.h>
#include <stdio.h>
#define SOCKETNAME "mynewsocket"
int main(void){
char buffer[1024];
int n, sock , nsock;
socklen_t len;
struct sockaddr_un name;
if((sock = socket(AF_UNIX, SOCK_STREAM, 0))<0){
perror("server: socket");
exit(1);
}
memset(&name, 0, sizeof(struct sockaddr_un));
name.sun_family = AF_UNIX;
strcpy(name.sun_path, SOCKETNAME);
len = sizeof(name.sun_family) + strlen(name.sun_path);
unlink ( name.sun_path ) ;
if (bind(sock, (struct sockaddr *) &name, SUN_LEN(&name)) < 0) {
perror("server: bind");
exit(1);
}
if (listen(sock, 5) < 0) {
perror("server: listen");
exit(1);
}
if ((nsock = accept(sock, (struct sockaddr *) &name, &len)) < 0) {
perror("server: accept");
exit(1);
}
n=read(nsock,buffer,80);
printf("A connection has been established\n");
write(1,buffer,n);
write(nsock,"I got your message\n",19);
close(nsock);
close(sock);
exit(0);
}
和客户......
//client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/un.h>
#include <stdio.h>
#define SOCKETNAME "mynewsocket"
int main(void){
char buffer [1024];
int n, sock, len;
struct sockaddr_un name;
if((sock = socket(AF_UNIX, SOCK_STREAM, 0))<0){
perror("client: socket");
exit(1);
}
memset(&name, 0, sizeof(struct sockaddr_un));
name. sun_family = AF_UNIX;
strcpy(name.sun_path, SOCKETNAME);
len = sizeof(name.sun_family) + strlen(name.sun_path);
unlink ( name.sun_path ) ;
if (connect(sock, (struct sockaddr *) &name, SUN_LEN(&name)) < 0) {
perror("client: connect");
exit(1);
}
printf("Please enter your message: ");
bzero(buffer,82);
fgets(buffer,80,stdin);
write(sock,buffer,strlen(buffer));
n=read(sock,buffer,80);
printf("The return message was\n");
write(1,buffer,n);
close(sock);
exit(0);
}
要运行这两个程序,首先编译并按如下方式运行:
./server &
./client
当我运行这两个程序时,服务器执行正常但客户端执行时出现错误No such file or directory
这是为什么?我的代码出了什么问题?
答案 0 :(得分:1)
unlink ( name.sun_path ) ;
为什么要取消关联?这是客户端和服务器的重要点!服务器可以在文件系统开始运行时在文件系统上创建文件,并在文件系统退出时取消链接。 (但这不是必需的)
客户端使用该文件来查找服务器。 (te&#34; secret&#34;他们共享的是套接字文件的位置和名称。
AF_UNIX使用文件系统作为命名空间(文件名而不是ip-addresses + portnumbers)在内部,(最有可能){dev_id,inodenumber}用作&#34; key&#34;识别套接字/文件描述符