一般在我们自己的主机上通信的时候,前面也讲到过可以使用pipe,fifo,msg,共享内存之类,如果你想使用套接字的话,当然TCP/IP的套接字也是可以的,只要指定server的IP = 127.0.0.1 或者你的当前主机的实际接入网络的IP也是可以的!但是相对与此处的UNIX domain来说,在效率上可能会低一点点、、、
UNIX domain的实际操作和前面的TCP/IP中的实际的操作的框架流程是差不多的!只是其中的细节的变化要注意!
代码贴下:
server端:
-
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/un.h>
-
- #define FILE "UNIX_DOMAIN" //!> 有点像FIFO中的文件是吧,呵呵
- #define MAXSIZE 1024
- #define MAXBACK 100
-
- int main( int argc, char ** argv )
- {
- int listen_fd;
- int conn_fd;
- int len;
- char recv[MAXSIZE];
- struct sockaddr_un servaddr;
- struct sockaddr_un childaddr;
-
- unlink( FILE );
-
-
-
- if( ( listen_fd = socket( AF_UNIX, SOCK_STREAM, 0 ) ) == -1 )
- {
- printf("Socket error : %d\n", errno);
- exit( EXIT_FAILURE );
- }
-
- servaddr.sun_family=AF_UNIX;
- strncpy( servaddr.sun_path, FILE, sizeof( servaddr.sun_path ) - 1 );
-
-
-
- if( bind( listen_fd, ( struct sockaddr * )&servaddr, sizeof( servaddr ) ) == -1 )
- {
- printf("Bind Error : %d\n", errno);
- close( listen_fd );
- unlink( FILE );
- exit( EXIT_FAILURE );
- }
-
-
-
- if( listen( listen_fd, MAXBACK ) == -1 )
- {
- printf("Listen error : %d\n", errno);
- close( listen_fd );
- unlink( FILE );
- exit( EXIT_FAILURE );
- }
-
- len = sizeof( childaddr );
-
- while( 1 )
- {
-
- if( ( conn_fd = accept( listen_fd, ( struct sockaddr *)&childaddr, &len ) ) == -1 )
- {
- printf("Accept Error : %d\n", errno);
- close( listen_fd );
- unlink( FILE );
- exit( EXIT_FAILURE );
- }
-
- while( 1 )
- {
- memset( recv, 0, sizeof( recv ) );
- len = read( conn_fd, recv, sizeof( recv ) );
-
- if( len == 0 )
- {
- close( conn_fd );
- break;
- }
- else if( len < 0 )
- {
- printf("Read error... : %d\n", errno);
- unlink( FILE );
- close( conn_fd );
- close( listen_fd );
- exit( EXIT_FAILURE );
- }
- else
- {
- len = strlen( recv );
- recv[len] = '\0';
-
- write( conn_fd, recv, strlen( recv ) );
- }
- }
-
- }
-
- unlink( FILE );
- close( conn_fd );
- close( listen_fd );
-
- return 0;
- }