PracticeDev/study_clang/ipc_test/unix_socket/tcp/client_tcp.cpp

81 lines
2.2 KiB
C++
Raw Normal View History

2022-12-20 17:31:11 +08:00
/*************************************************************************
> File Name: ipc_tcp_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/ipc_tcp_server.sock";
const char* client_file = "/tmp/ipc_tcp_client.sock";
int main(int argc,char** argv)
{
int socket_fd = socket(AF_UNIX,SOCK_STREAM,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];
/* --------DIFF, ipc tcp only------------ */
int newcon = -1;
newcon = connect(socket_fd,(sockaddr*)&serveraddr,addrlen);
if (newcon < 0){
perror("client connect");
}
/* ---------------end------------ */
while(1)
{
strcpy(msg_buf, "How are you !!!");
int ssize = send(socket_fd, msg_buf, sizeof msg_buf, 0);
if (ssize < 0)
{
perror("client send");
continue;
}
int rsize = recv(socket_fd, msg_buf, sizeof(msg_buf), 0);
if (rsize < 0)
{
perror("client recv");
continue;
}
cout << "I'm Unix socket(TCP) clientreceive a msg :" << msg_buf << endl;
sleep(1);
}
if (close(socket_fd) < 0)
{
perror("close");
return -1;
}
return 0;
}