PracticeDev/study_clang/ipc_test/unix_socket/udpserver.cpp

97 lines
1.9 KiB
C++
Raw Normal View History

2022-12-20 17:31:11 +08:00
/*************************************************************************
> File Name: udpserver.cpp
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 13 Jan 2021 09:53:06 AM CST
************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <iostream>
#include <unistd.h>
using namespace std;
char* server_file = "server.sock";
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));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,server_file);
if (access(addr.sun_path,0) != -1)
{
remove(addr.sun_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: " << clientaddr.sun_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;
}