#include<sys/types.h> #include<sys/socket.h> ssize_t recv(int sockfd, void *buf, size_t len, int flags); ssize_t send(int sockfd, const void *buf, size_t len, int flags);
TCP 提供的是面向连接的、可靠的、字节流服务。TCP 的服务器端和客户端编程流程为:
// TCP Server.c #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<arpa/inet.h> #include<netinet/in.h> int main(void) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); assert(sockfd != -1); struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int res = bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr)); assert(res != -1); res = listen(sockfd, 5); assert(res != -1); while (1) { struct sockaddr_in caddr; socklen_t len = sizeof(caddr); int c = accept(sockfd, (struct sockaddr*)&caddr, &len); if (c == -1) { perror("accept error"); continue; } printf("accept c = %d\n", c); char data[128] = {0}; int n = recv (c, data, 127, 0); printf("n = %d, buff = %s\n", n, data); send(c, "OK", 2, 0); close(c); } close(sockfd); exit(0); }
//TCP Client.c #include<stdio.h> #include<assert.h> #include<string.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<arpa/inet.h> #include<netinet/in.h> int main(void) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); assert(sockfd != -1); struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int res = connect(sockfd, (struct sockaddr*)&saddr, sizeof(saddr)); assert(res != -1); printf("Please input data:\n"); char buff[128] = {0}; fgets(buff, 128, stdin); send(sockfd, buff, strlen(buff) - 1, 0); char data[128] = {0}; int n = recv(sockfd, data, 127, 0); printf("%s\n", data); close(sockfd); exit(0); }