手机版
你好,游客 登录 注册
背景:
阅读新闻

UNIX domain ( UNIX 预协议 ) 实例

[日期:2012-03-22] 来源:Linux社区  作者:shanshanpt [字体:大 中 小]

cilent端:

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <errno.h>   
  4. #include <string.h>   
  5. #include <sys/types.h>   
  6. #include <sys/socket.h>   
  7. #include <sys/un.h>   
  8.   
  9. #define     FILE            "UNIX_DOMAIN" //!> 其实作用有点像PORT不是吗,:-)   
  10. #define     MAXSIZE     1024   
  11.   
  12. int main( int argc, char ** argv )  
  13. {  
  14.     int         conn_fd;  
  15.     int         i_index;  
  16.     int         len;  
  17.     char    send_recv[MAXSIZE];  
  18.     struct  sockaddr_un servaddr;  
  19.       
  20.     if( ( conn_fd = socket( AF_UNIX, SOCK_STREAM, 0 ) ) == -1 )  
  21.     {  
  22.         printf("Socket Error... %d\n", errno);  
  23.         exit( EXIT_FAILURE );  
  24.     }  
  25.       
  26.     servaddr.sun_family = AF_UNIX;  
  27.         strcpy(servaddr.sun_path, FILE );  
  28.       
  29.     //!> connect   
  30.     //!>    
  31.     if( connect( conn_fd, ( struct sockaddr * )&servaddr, sizeof( servaddr ) ) == -1 )  
  32.     {  
  33.         printf("Connect Error... : %d\n", errno);  
  34.         close( conn_fd );  
  35.         exit( EXIT_FAILURE );  
  36.     }  
  37.       
  38.     i_index = 0;  
  39.       
  40.     while( 1 )  
  41.     {  
  42.         memset( send_recv, 0, sizeof( send_recv ) );        //!> 注意此步需要   
  43.           
  44.         sprintf(send_recv, "Client Send : %d\n", i_index++);  
  45.           
  46.         write( conn_fd, send_recv, strlen( send_recv ) );   //!> 写数据   
  47.           
  48.         sleep( 1 );  
  49.           
  50.         memset( send_recv, 0, sizeof( send_recv ) );  
  51.         len = read( conn_fd, send_recv, sizeof( send_recv ) );  //!> 读数据   
  52.         if( len > 0 )  
  53.         {  
  54.             printf("Client Get ---> %s\n", send_recv);  
  55.         }  
  56.           
  57.         sleep( 1 );  
  58.       
  59.     }  
  60.       
  61.     close( conn_fd );  
  62.     return 0;  
  63. }  

编译与运行:

            gcc -o server server.c

            gcc -o client client.c

            ./server  ( 可以使用后台& )

            ./client


好了这个代码比较简单,就不说什么了~

linux
相关资讯       UNIX 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款