91 lines
2.4 KiB
C++
91 lines
2.4 KiB
C++
/*************************************************************************
|
|
> File Name: ipc_tcp_server.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 <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";
|
|
|
|
int main(int argc,char** argv)
|
|
{
|
|
int socket_fd = socket(AF_UNIX,SOCK_STREAM,0);
|
|
if (socket_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(socket_fd,(sockaddr*)&addr,sizeof(addr)) < 0)
|
|
{
|
|
perror("bind");
|
|
return -1;
|
|
}
|
|
/* --------DIFF, ipc tcp only------------ */
|
|
if (listen(socket_fd,12) < 0)
|
|
{
|
|
perror("listen");
|
|
return -1;
|
|
}
|
|
/* ---------------end------------ */
|
|
struct sockaddr_un clientaddr;
|
|
socklen_t addrlen = sizeof(clientaddr);
|
|
char msg_buf[1024];
|
|
/* --------DIFF, ipc tcp only------------ */
|
|
int newcon = -1;
|
|
newcon = accept(socket_fd,(sockaddr*)&clientaddr,&addrlen);
|
|
if (newcon < 0)
|
|
{
|
|
perror("accept");
|
|
return -1;
|
|
}
|
|
/* ---------------end------------ */
|
|
while (1)
|
|
{
|
|
memset(msg_buf,'\0',1024);
|
|
int rsize = recv(newcon,msg_buf,sizeof(msg_buf),0);
|
|
if (rsize < 0)
|
|
{
|
|
perror("server recv error!");
|
|
break;
|
|
}
|
|
cout << "I'm Unix socket(TCP) server, recv a msg:" << msg_buf << " from: " << clientaddr.sun_path << endl;
|
|
strcpy(msg_buf, "OK,I got it!");
|
|
int ssize = send(newcon, msg_buf, sizeof msg_buf, 0);
|
|
if (ssize < 0)
|
|
{
|
|
perror("server send error!");
|
|
break;
|
|
}
|
|
sleep(1);
|
|
}
|
|
/* --------DIFF, ipc tcp only------------ */
|
|
if (close(newcon) < 0)
|
|
{
|
|
perror("close accept");
|
|
return -1;
|
|
}
|
|
/* ---------------end------------ */
|
|
if (close(socket_fd) < 0)
|
|
{
|
|
perror("close socket");
|
|
return -1;
|
|
}
|
|
return 0;
|
|
} |