PracticeDev/study_clang/ipc_test/unix_socket/udp/client_udp.cpp

74 lines
2.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*************************************************************************
> File Name: ipc_udp_client.cpp
> Author: TianLun Song
> Mail: songtianlun@frytea.com
> Blog: https://blog.frytea.com
> Created Time: Wed 13 Jan 2021 10:14:09 AM CST
************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <memory.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
using namespace std;
const char* server_file = "/tmp/criu/ipc_udp_server.sock";
const char* client_file = "/tmp/criu/ipc_udp_client.sock";
int main(int argc,char** argv)
{
int socket_fd = socket(AF_UNIX,SOCK_DGRAM,0);
if (socket_fd < 0)
{
perror("client socket");
return -1;
}
struct sockaddr_un client_addr;
memset(&client_addr,0,sizeof(client_addr));
client_addr.sun_family = AF_UNIX;
strcpy(client_addr.sun_path,client_file);
if (access(client_addr.sun_path,0) != -1)
{
remove(client_addr.sun_path);
}
if(bind(socket_fd,(sockaddr*)&client_addr,sizeof(client_addr)) < 0)
{
perror("client bind");
return -1;
}
struct sockaddr_un serveraddr;
memset(&serveraddr,0,sizeof(serveraddr));
socklen_t addrlen = sizeof(serveraddr);
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path,server_file);
char msg_buf[1024];
while(1)
{
strcpy(msg_buf, "How are you !!!");
int ssize = sendto(socket_fd, msg_buf, sizeof msg_buf, 0, (sockaddr*)&serveraddr,addrlen);
if (ssize < 0)
{
perror("client sendto");
continue;
}
int rsize = recvfrom(socket_fd, msg_buf, sizeof(msg_buf), 0,(sockaddr*)&serveraddr, &addrlen);
if (rsize < 0)
{
perror("client recv");
continue;
}
cout << "I'm Unix socket(UDP) clientreceive a msg :" << msg_buf << endl;
sleep(1);
}
if (close(socket_fd) < 0)
{
perror("close");
return -1;
}
return 0;
}