可以实现通信的代码实现,拿去用!
原文来自:/uid-26790551-id-3171897.html
服务器端:
#include
#include
#include
#include
#include
#include
#define UNIX_DOMAIN "/tmp/UNIX.domain"
int main(void)
{
int lsn_fd, apt_fd;
struct sockaddr_un srv_addr;
struct sockaddr_un clt_addr;
socklen_t clt_len;
int ret;
int i;
char recv_buf[1024];
char send_buf[1024];
//create socket to bind local IP and PORT
lsn_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(lsn_fd < 0)
{
perror("can't create communication socket!");
return 1;
}
//create local IP and PORT
srv_addr.sun_family = AF_UNIX;
strncpy(srv_addr.sun_path, UNIX_DOMAIN, sizeof(srv_addr.sun_path) - 1);
unlink(UNIX_DOMAIN);
//bind sockfd and sockaddr
ret = bind(lsn_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
if(ret == -1)
{
perror("can't bind local sockaddr!");
close(lsn_fd);
unlink(UNIX_DOMAIN);
return 1;
}
//listen lsn_fd, try listen 1
ret = listen(lsn_fd, 1);
if(ret == -1)
{
perror("can't listen client connect request");
close(lsn_fd);
unlink(UNIX_DOMAIN);
return 1;
}
clt_len = sizeof(clt_addr);
while(1)
{
apt_fd = accept(lsn_fd, (struct sockaddr*)&clt_addr, &clt_len);
if(apt_fd < 0)
{
perror("can't listen client connect request");
close(lsn_fd);
unlink(UNIX_DOMAIN);
return 1;
}
printf("received a connection\n");
printf("send message to client\n");
memset(send_buf, 0, 1024);
strcpy(send_buf, "Hello, you have connected to server succeed");
int snd_num = write(apt_fd, send_buf, 1024);
if(snd_num != 1024)
{
perror("send messge to client failed\n");
close(apt_fd);
close(lsn_fd);
unlink(UNIX_DOMAIN);
return 1;
}
//read and printf client info
printf("============info=================\n");
for(i = 0; i < 4; i++)
{
memset(recv_buf, 0, 1024);
int rcv_num = read(apt_fd, recv_buf, sizeof(recv_buf));
printf("Message from client (%d) :%s\n", rcv_num, recv_buf);
}
}
close(apt_fd);
close(lsn_fd);
unlink(UNIX_DOMAIN);
return 0;
}
客户端:
#include
#include
#include
#include
#include
#define UNIX_DOMAIN "/tmp/UNIX.domain"
int main(void)
{
int connect_fd;
struct sockaddr_un srv_addr;
char snd_buf[1024];
char rcv_buf[1024];
int ret;
int i;
//create client socket
connect_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(connect_fd < 0)
{
perror("client create socket failed");
return 1;
}
//set server sockaddr_un
srv_addr.sun_family = AF_UNIX;
strcpy(srv_addr.sun_path, UNIX_DOMAIN);
//connect to server
ret = connect(connect_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
if(ret == -1)
{
perror("connect to server failed!");
close(connect_fd);
unlink(UNIX_DOMAIN);
return 1;
}
//receive message from server
memset(rcv_buf, 0, 1024);
int rcv_num = read(connect_fd, rcv_buf, sizeof(rcv_buf));
printf("receive message from server (%d) :%s\n", rcv_num, rcv_buf);
//printf("\n");
//send message to server
memset(snd_buf, 0, 1024);
strcpy(snd_buf, "message from client");
printf("sizeof(snd_buf): %d\n", sizeof(snd_buf));
sleep(2000);
//send message to server
for(i = 0; i < 4; i++)
{
write(connect_fd, snd_buf, sizeof(snd_buf));
}
close(connect_fd);
return 0;
}