1. /*./client unix_domain_file */
    2. #include "net.h"
    3. void usage (char *s)
    4. {
    5. printf ("\n%s unix_domain_file\n\n", s);
    6. }
    7. int main (int argc, char **argv)
    8. {
    9. int fd = -1;
    10. int port = -1;
    11. struct sockaddr_un sun;
    12. if (argc != 2) {
    13. usage (argv[0]);
    14. exit (1);
    15. }
    16. /* 1. 创建socket fd */
    17. if ((fd = socket (AF_LOCAL, SOCK_STREAM, 0)) < 0) {
    18. perror ("socket");
    19. exit (1);
    20. }
    21. /*2.连接服务器 */
    22. /*2.1 填充struct sockaddr_un结构体变量 */
    23. bzero (&sun, sizeof (sun));
    24. sun.sun_family = AF_LOCAL;
    25. /*确保UNIX_DOMAIN_FILE要先存在并且可写,不存在则退出 */
    26. if( access(UNIX_DOMAIN_FILE, F_OK| W_OK) < 0){
    27. exit(1);
    28. }
    29. strncpy(sun.sun_path, UNIX_DOMAIN_FILE, strlen( UNIX_DOMAIN_FILE));
    30. if (connect (fd, (struct sockaddr *) &sun, sizeof (sun)) < 0) {
    31. perror ("connect");
    32. exit (1);
    33. }
    34. printf ("Unix domain Client staring...OK!\n");
    35. int ret = -1;
    36. fd_set rset;
    37. int maxfd = -1;
    38. struct timeval tout;
    39. char buf[BUFSIZ];
    40. while (1) {
    41. FD_ZERO (&rset);
    42. FD_SET (0, &rset);
    43. FD_SET (fd, &rset);
    44. maxfd = fd;
    45. tout.tv_sec = 5;
    46. tout.tv_usec = 0;
    47. select (maxfd + 1, &rset, NULL, NULL, &tout);
    48. if (FD_ISSET (0, &rset)) { //标准键盘上有输入
    49. //读取键盘输入,发送到网络套接字fd
    50. bzero (buf, BUFSIZ);
    51. do {
    52. ret = read (0, buf, BUFSIZ - 1);
    53. } while (ret < 0 && EINTR == errno);
    54. if (ret < 0) {
    55. perror ("read");
    56. continue;
    57. }
    58. if (!ret)
    59. continue;
    60. if (write (fd, buf, strlen (buf)) < 0) {
    61. perror ("write() to socket");
    62. continue;
    63. }
    64. if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    65. printf ("Client is exiting!\n");
    66. break;
    67. }
    68. }
    69. if (FD_ISSET (fd, &rset)) { //服务器给发送过来了数据
    70. //读取套接字数据,处理
    71. bzero (buf, BUFSIZ);
    72. do {
    73. ret = read (fd, buf, BUFSIZ - 1);
    74. } while (ret < 0 && EINTR == errno);
    75. if (ret < 0) {
    76. perror ("read from socket");
    77. continue;
    78. }
    79. if (!ret)
    80. break; /* 服务器关闭 */
    81. //There is a BUG,FIXME!!
    82. printf ("server said: %s\n", buf);
    83. if ((strlen(buf) > strlen(SERV_RESP_STR))
    84. && !strncasecmp (buf+strlen(SERV_RESP_STR), QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    85. printf ("Sender Client is exiting!\n");
    86. break;
    87. }
    88. }
    89. }
    90. /*4.关闭套接字 */
    91. close (fd);
    92. }