2.6.2 客户端

    1. #include <stdlib.h>
    2. #include <string.h>
    3. #include <strings.h>
    4. #include <sys/types.h>
    5. #include <sys/socket.h>
    6. #include <arpa/inet.h>
    7. #include <unistd.h>
    8. #include <fcntl.h>
    9. #define MAX_LINE (1024)
    10. #define SERVER_PORT (7778)
    11. void setnoblocking(int fd)
    12. {
    13. int opts = 0;
    14. opts = fcntl(fd, F_GETFL);
    15. opts = opts | O_NONBLOCK;
    16. fcntl(fd, F_SETFL);
    17. }
    18. int main(int argc, char **argv)
    19. {
    20. int sockfd;
    21. char recvline[MAX_LINE + 1] = {0};
    22. struct sockaddr_in server_addr;
    23. if (argc != 2) {
    24. fprintf(stderr, "usage ./client <SERVER_IP>\n");
    25. exit(0);
    26. }
    27. if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    28. fprintf(stderr, "socket error");
    29. exit(0);
    30. }
    31. // server addr 赋值
    32. bzero(&server_addr, sizeof(server_addr));
    33. server_addr.sin_family = AF_INET;
    34. server_addr.sin_port = htons(SERVER_PORT);
    35. if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) <= 0) {
    36. fprintf(stderr, "inet_pton error for %s", argv[1]);
    37. exit(0);
    38. }
    39. // 链接服务端
    40. if (connect(sockfd, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0) {
    41. perror("connect");
    42. fprintf(stderr, "connect error\n");
    43. exit(0);
    44. }
    45. setnoblocking(sockfd);
    46. char input[100];
    47. int n = 0;
    48. int count = 0;
    49. // 不断的从标准输入字符串
    50. printf("[send] %s\n", input);
    51. n = 0;
    52. // 把输入的字符串发送 到 服务器中去
    53. n = send(sockfd, input, strlen(input), 0);
    54. if (n < 0) {
    55. perror("send");
    56. }
    57. n = 0;
    58. count = 0;
    59. // 读取 服务器返回的数据
    60. while (1)
    61. {
    62. n = read(sockfd, recvline + count, MAX_LINE);
    63. if (n == MAX_LINE)
    64. {
    65. count += n;
    66. continue;
    67. }
    68. else if (n < 0){
    69. perror("recv");
    70. break;
    71. }
    72. else {
    73. count += n;
    74. recvline[count] = '\0';
    75. printf("[recv] %s\n", recvline);
    76. break;
    77. }
    78. }
    79. }
    80. }