tcp本地套接字客户端流程:
?调用创建套接字
?调用bind函数将文件描述和文件进行绑定.
不是必须的, 若无显示绑定会进行隐式绑定,但服务器不知道谁连接了.
?调用函数连接服务端
?循环通信read-write
?关闭文件描述符 close
//本地通信客户端
.c
#include #include #include #include #include #include #include #include int main(){//创建socketint cfd = socket(AF_UNIX, SOCK_STREAM, 0);if(cfd<0){perror("socket error");return -1;}//删除socket文件,避免bind失败unlink("./client.sock");//绑定bindstruct sockaddr_un client;bzero(&client, sizeof(client));client.sun_family = AF_UNIX;strcpy(client.sun_path, "./client.sock"); int ret = bind(cfd, (struct sockaddr *)&client, sizeof(client));if(ret<0){perror("bind error");return -1;}struct sockaddr_un serv;bzero(&serv, sizeof(serv));serv.sun_family = AF_UNIX;strcpy(serv.sun_path, "./server.sock");ret = connect(cfd, (struct sockaddr *)&serv, sizeof(serv));if(ret<0){perror("connect error"); return -1;}int n;char buf[1024];while(1){memset(buf, 0x00, sizeof(buf));n = read(STDIN_FILENO, buf, sizeof(buf));//发送数据write(cfd, buf, n);//读数据memset(buf, 0x00, sizeof(buf));n = read(cfd, buf, sizeof(buf));if(n<=0){printf("read error or client close, n==[%d]\n", n);break;}printf("n==[%d], buf==[%s]\n", n, buf);}close(cfd);return 0;}
.c
//本地socket通信服务端#include #include #include #include #include #include #include #include int main(){//创建socketint lfd = socket(AF_UNIX, SOCK_STREAM, 0);if(lfd<0){perror("socket error");return -1;}//删除socket文件,避免bind失败unlink("./server.sock");//绑定bindstruct sockaddr_un serv;bzero(&serv, sizeof(serv));serv.sun_family = AF_UNIX;strcpy(serv.sun_path, "./server.sock"); int ret = bind(lfd, (struct sockaddr *)&serv, sizeof(serv));if(ret<0){perror("bind error");return -1;}//监听listenlisten(lfd, 10);//接收新的连接-acceptstruct sockaddr_un client;bzero(&client, sizeof(client));int len = sizeof(client);int cfd = accept(lfd, (struct sockaddr *)&client, &len);if(cfd<0){perror("accept error"); return -1;}printf("client->[%s]\n", client.sun_path);int n;char buf[1024];while(1){//读数据memset(buf, 0x00, sizeof(buf));n = read(cfd, buf, sizeof(buf));if(n<=0){printf("read error or client close, n==[%d]\n", n);break;}printf("n==[%d], buf==[%s]\n", n, buf);//发送数据write(cfd, buf, n);}close(lfd);return 0;}
size = ( , ) +(un.); # (type, ) ((int)&((type *)0)->)
【linux网络编程5、线程池、本地socket、offset函数、UDP通信】//调用offset函数测试结构体成员变量的偏移量#include #include #include int main(void){struct s {int i;char c;double d;char a[1];};/* Output is compiler dependent */printf("offsets: i=%zd; c=%zd; d=%zd a=%zd\n",offsetof(struct s, i), offsetof(struct s, c),offsetof(struct s, d), offsetof(struct s, a));printf("sizeof(struct s)=%zd\n", sizeof(struct s));return 0;}