🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## Unix域套接字 - 套接字( socket原是网络通信中使用的术语 - Unⅸx系统提供的域套接字提供了网络套接字类似的功能 ## 流程 **服务端** 1. 创建套接字 2. 绑定(bind)套接字 3. 监听( isten)套接字 4. 接收&处理信息 **客户端** 1. 创建套接字 2. 连接套接字 3. 发送信息 ## 示例 <details> <summary>server.cpp</summary> ``` #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <string.h> #include <string.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #define SOCKET_PATH "./domainsokcet" #define MSG_SIZE 2048 int main() { int socket_fd, accept_fd; int ret = 0; socklen_t addr_len; char msg[MSG_SIZE]; struct sockaddr_un server_addr; // 1.创建套接字 socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if (-1 == socket_fd) { std::cout << "Socket create failed!" << std::endl; return -1; } // 移除已有套接字路径 remove(SOCKET_PATH); //内存区域置零 bzero(&server_addr, sizeof(server_addr)); server_addr.sun_family = PF_UNIX; strcpy(server_addr.sun_path, SOCKET_PATH); // 2. 绑定域套接字 std::cout << "Binding socket... " << std::endl; ret = bind(socket_fd, (sockaddr *)&server_addr, sizeof(server_addr)); if (0 > ret) { std::cout << "Binding failed! " << std::endl; return -1; } // 3. 监听套接字 std::cout << "Listening socket... " << std::endl; ret = listen(socket_fd, 10); if (-1 == ret) { std::cout << "Listening failed... " << std::endl; return -1; } std::cout << "Waiting for new requests... " << std::endl; accept_fd = accept(socket_fd, NULL, NULL); bzero(msg, MSG_SIZE); // 4. 接收&处理信息 while (true) { recv(accept_fd, msg, MSG_SIZE, 0); std::cout << "Received message from remote:" << msg << std::endl; sleep(1); } close(accept_fd); close(socket_fd); return 0; } ``` </details> <br /> <details> <summary>client.php</summary> ``` #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <string.h> #include <string.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> #include <iostream> // #define SOCKET_PATH "./domainsokcet" #define MSG_SIZE 2048 int main() { int socket_fd; int ret = 0; char msg[MSG_SIZE]; struct sockaddr_un server_addr; // 1.创建套接字 socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if (-1 == socket_fd) { std::cout << "Socket create failed!" << std::endl; return -1; } //内存区域置零 bzero(&server_addr, sizeof(server_addr)); server_addr.sun_family = PF_UNIX; strcpy(server_addr.sun_path, SOCKET_PATH); // 2. 链接套接字 ret = connect(socket_fd,(sockaddr*)&(server_addr),sizeof(server_addr)); if(-1 ==ret){ std::cout << "Connect socket failed!" << std::endl; return -1; } while (true) { std::cout << "Input message >>>" ; fgets(msg,MSG_SEND,stdin); ret = send(socket_fd,msg,MSG_SIZE,0); } close(socket_fd); return 0; } ``` </details> <br /> 编译运行 ``` > g++ server.cpp -o server && g++ client.cpp -o client > ./client Input message >>>ww Input message >>>aaa ``` ``` > ./server Binding socket... Listening socket... Waiting for new requests... Received message from remote:ww Received message from remote:aaa ```