admin 管理员组

文章数量: 887021


2023年12月22日发(作者:python header)

memset(&addr,0,sizeof(addr)); _family = AF_UNIX; strcpy(_path,server_file); if (access(_path,0) != -1) { remove(_path); } if(bind(fd,(sockaddr*)&addr,sizeof(addr)) < 0) { perror("bind"); return -1; } struct sockaddr_un clientaddr; socklen_t len = sizeof(clientaddr); char msgrecv[1024];

while (1) { memset(msgrecv,'0',1024); int size = recvfrom(fd,msgrecv,sizeof(msgrecv),0,(sockaddr*)&clientaddr,&len); if (size < 0) { perror("recv"); return -1; } cout << "I'm server,receive a msg: " << msgrecv << " from: " << _path << endl; if (strncmp("quit",msgrecv,4) == 0) { cout << "Server is exiting!" << endl; break; } char *p = "OK,I got id!"; int ssize = sendto(fd,p,strlen(p),0,(sockaddr*)&clientaddr,len); if (ssize < 0) { perror("sendto"); return -1; } sleep(1); } if (close(fd) < 0) { perror("close"); return -1; } return 0;

}

代码很简单,udpserver 作为服务端,循环接受和打印消息。如果收到了 quit 的消息就退出。#include #include #include #include #include #include using namespace std;char* server_file = "";char* client_file = "";int main(int argc,char** argv){ int fd = socket(AF_UNIX,SOCK_DGRAM,0); if (fd < 0) { perror("socket"); return -1; } struct sockaddr_un addr; memset(&addr,0,sizeof(addr)); _family = AF_UNIX; strcpy(_path,client_file); if (access(_path,0) != -1) { remove(_path); } if(bind(fd,(sockaddr*)&addr,sizeof(addr)) < 0) { perror("bind"); return -1; } struct sockaddr_un clientaddr; socklen_t len = sizeof(clientaddr); char msgrecv[1024]; struct sockaddr_un serveraddr; memset(&serveraddr,0,sizeof(serveraddr)); _family = AF_UNIX; strcpy(_path,server_file);

char *p = "Hello,how are you?"; int ssize = sendto(fd,p,strlen(p),0,(sockaddr*)&serveraddr,len); if (ssize < 0) { perror("sendto"); return -1; }


本文标签: 服务端 退出 接受