Server
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h> int main(int argc, char* argv[]) {int fd = socket(PF_INET, SOCK_STREAM, 0);if (fd == -1) {perror("socket");return -1;}struct sockaddr_in saddr;memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET;saddr.sin_port = htons(9999);saddr.sin_addr.s_addr = INADDR_ANY; int ret = bind(fd, (struct sockaddr*)&saddr, sizeof(saddr));if (ret == -1) {perror("bind");return -1;}ret = listen(fd, SOMAXCONN); if (ret == -1) {perror("listen");return -1;}struct sockaddr_in caddr;memset(&caddr, 0, sizeof(caddr));socklen_t caddr_len = sizeof(caddr);int cfd = accept(fd, (struct sockaddr*)&caddr, &caddr_len); if (cfd == -1) {perror("accept");return -1;}printf("client socket %d, Address: %s:%d\n", cfd, inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));while (1) {char buf[1024];int len = recv(cfd, buf, sizeof(buf), 0);if (len > 0) {printf("client say: %s\n", buf);send(cfd, buf, len, 0); } else if (len == 0) {printf("客户端已经断开连接...\n");break;} else if (len == -1) {perror("recv");break;}} close(cfd);close(fd);return 0;
}
Client
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h> int main(int argc, char* argv[]) {int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd == -1) {perror("socket");return -1;}struct sockaddr_in saddr;memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET;saddr.sin_port = htons(9999);inet_pton(AF_INET, "127.0.0.1", &saddr.sin_addr.s_addr);saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int ret = connect(fd, (struct sockaddr*)&saddr, sizeof(saddr));if (ret == -1) {perror("connect");return -1;}printf("socket connect successful!\n");int number = 0;while (1) {char buf[1024];sprintf(buf, "hello, message number #%d...\n", number++); send(fd, buf, strlen(buf)+1, 0); memset(buf, 0, sizeof(buf)); int len = recv(fd, buf, sizeof(buf), 0);if (len > 0) {printf("server say: %s\n", buf);} else if (len == 0) {printf("服务器已经断开连接...\n");break;} else if (len == -1) {perror("recv");break;}sleep(1); } close(fd);return 0;
}