SOCKET编程之使用AF_UNIX实现本机数据流通信示例

时间:2022-03-30 22:29:14

本程序由服务器端程序和客户端程序两部分组成。

服务器端程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>

int main()
{
 int server_sockfd,client_sockfd;
 int server_len,client_len;
 struct sockaddr_un server_address;
 struct sockaddr_un client_address;
 int i,byte;
 char ch_send,ch_rec;
 unlink("server_socket");
 server_sockfd=socket(AF_UNIX,SOCK_STREAM,0);
 if(server_sockfd==-1)
 {
  perror("socket");
  exit(1);
 }
 server_address.sun_family=AF_UNIX;
 strcpy(server_address.sun_path,"server_socket");
 server_len=sizeof(server_address);
 
 bind(server_sockfd,(struct sockaddr *)&server_address,server_len);
 listen(server_sockfd,5);
 printf("server waiting for client connect\n");
 client_len=sizeof(client_address);
 client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address,(socklen_t *)&client_len);
 printf("the server wait for client data\n");
 for(i=0,ch_send='1';i<5;i++,ch_send++)
 {
  if((byte=read(client_sockfd,&ch_rec,1))==-1)
  {
   perror("read");
   exit(1);
  }
  printf("the character receiver from client is %c\n",ch_rec);
  sleep(1);
  if(write(client_sockfd,&ch_send,1)==-1)
  {
   perror("write");
   exit(1);
  }
 
 }
 close(client_sockfd);
 unlink("server_socket");
 return 0;
}

客户端程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>

int main()
{
 int sockfd;
 int len;
 struct sockaddr_un address;
 int result;
 int i,byte;
 char ch_recv,ch_send;
 sockfd=socket(AF_UNIX,SOCK_STREAM,0);
 if(sockfd==-1)
 {
  perror("socket");
  exit(1);
 }
 address.sun_family=AF_UNIX;
 strcpy(address.sun_path,"server_socket");
 len=sizeof(address);
 result=connect(sockfd,(struct sockaddr*)&address,len);
 if(result==-1)
 {
  printf("ensure the server is up\n");
  perror("connect");
  exit(1);
 }
 for(i=0,ch_send='A';i<5;i++,ch_send++)
 {
  if(write(sockfd,&ch_send,1)==-1)
  {
   perror("write");
   exit(1);
  }
  if(read(sockfd,&ch_recv,1)==-1)
  {
   perror("read");
   exit(1);
  }
  printf("receive from server is %c\n",ch_recv);
 }

 close(sockfd);
 return 0;
}

这个是socket的API函数的基础应用,我在这个基础上改编了一个较为复杂的程序,但不利于理解,所以还是把这个原始的贴出来,供借鉴