// tcp_s1 的客户端 #include #include #include #include #include #include // bzero #include // atoi int main(int argc, char const *argv[]) { if (argc < 3) { printf("usage: %s server_ip port\n", argv[0]); return 1; } // TCP 的 socket 套接字类型 SOCK_STREAM int sock_fd = socket(AF_INET, SOCK_STREAM, 0); if (sock_fd < 0) { perror("socket"); return 1; } // 连接服务端 struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(argv[1]); server_addr.sin_port = htons(atoi(argv[2])); // 连接 if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0) { perror("connect"); close(sock_fd); return 1; } printf("connect ok\n"); while (1) { char buf[128] = ""; scanf("%s", buf); // 从键盘取数据 int send_len = send(sock_fd, buf, strlen(buf), 0); if (send_len == -1) { perror("send"); break; } if (strncmp(buf, "bye", 3) == 0) { break; } if (strncmp(buf, "clear", 5) == 0) { system("clear"); } memset(buf, 0, 128); send_len = recv(sock_fd, buf, 128, 0); if (send_len > 0) { printf("%s(%s): %s\n", argv[1], argv[2], buf); } } close(sock_fd); return 0; }