#include "../lib/sock_msg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8888 // 服务器端口号 #define IP "172.27.92.202" int main(int argc, char *argv[]) { int sockfd; // 连接套接字 struct sockaddr_in servaddr; // 服务器地址结构 char buf[BUFFER_SIZE]; // 缓冲区 int n; // 读写字节数 // 创建连接套接字,使用TCP协议 inet_pton(AF_INET, IP, &servaddr.sin_addr); sockfd = sock_init(0, servaddr.sin_addr.s_addr, PORT); // 循环从标准输入读取数据,并发送给服务器,然后接收服务器的回复,并打印 while (fgets(buf, BUFFER_SIZE, stdin) != NULL) { if (strncmp(buf, "exit\n", 4) == 0) { printf("Close the connection.\n"); break; } printf("send: %s\n", buf); sock_write(sockfd, buf, strlen(buf)); // 发送数据 // 清空buf memset(buf, 0, BUFFER_SIZE); printf("recv: %s\n", buf); n = sock_read(sockfd, buf, BUFFER_SIZE); // 接收数据 if (n == 0) { printf("the other side has been closed.\n"); break; } write(STDOUT_FILENO, buf, n); // 打印数据 } // 关闭连接套接字 sock_exit(sockfd); return 0; }