server端:
#include#include #include #include #include #include #include #define MAX_BUFF_SIZE 1024int main(int argc, char *argv[]){ int ret; int listenfd, connfd; struct sockaddr_in server_addr; int client_len; struct sockaddr_in client_addr; char buff[MAX_BUFF_SIZE]; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == -1) { perror("socket()"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(49001); ret = bind(listenfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (ret == -1) { perror("bind()"); return -1; } ret = listen(listenfd, 5); if (ret == -1) { perror("listen()"); close(listenfd); return -1; } while (1) { connfd = accept(listenfd,(struct sockaddr *)&client_addr, &client_len); if (connfd == -1) { perror("accept()"); continue; } memset(buff, 0, sizeof(buff)); recv(connfd, buff, sizeof(buff), 0); printf("%s\n", buff); memset(buff, 0, sizeof(buff)); strcpy(buff, "hello, client--- "); send(connfd, buff, strlen(buff)+1, 0); close(connfd); } close(listenfd); return 0;}
client端:
#include#include #include #include #include #include #include #define MAX_BUFF_SIZE 1024int main(int argc, char *argv[]){ int ret; int sockfd; struct sockaddr_in server_addr; char buff[MAX_BUFF_SIZE]; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(49001); while (1) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("socket()"); return -1; } ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (ret == -1) { perror("connect()"); return -1; } memset(buff, 0, sizeof(buff)); strcpy(buff, "hello, server--- "); ret = send(sockfd, buff, strlen(buff), 0); if (ret == -1) { perror("sendto()"); break; } memset(buff, 0, sizeof(buff)); ret = recv(sockfd, buff, sizeof(buff), 0); if (ret == -1) { perror("recv()"); break; } printf("%s\n", buff); close(sockfd); sleep(3); } return 0;}
遇到的问题:
1.设置server地址时,server、client端都没有设置 sin_family,此时 client 调用 send 之后进程就直接exit掉了,没有返回。
2.client端必须要关闭掉fd之后重新socket一个,否则会报
Transport endpoint is already connected
错误。