嵌入式Linux实现TCP/IP通信

2019-07-12 14:59发布

实现client向server发送数据。
server里面的rev要用nsockfdclient里面的send用sockfd
tcp_server代码:#include #include #include #include #include #include #include #include #include #include #define PORT 8088 // The port which is communicate with server #define BACKLOG 10 #define LENGTH 512 // Buffer length int main () { int iR; int sockfd; // Socket file descriptor int nsockfd; // New Socket file descriptor int num; int sin_size; // to store struct size char sdbuf[LENGTH]; // Send buffer char revbuf[LENGTH]; // Receive buffer struct sockaddr_in addr_local; struct sockaddr_in addr_remote; // char sendstr[16]= {"123456789 abcde"}; /* Get the Socket file descriptor */ if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) { printf ("ERROR: Failed to obtain Socket Despcritor. "); return (0); } else { printf ("OK: Obtain Socket Despcritor sucessfully. "); } /* Fill the local socket address struct */ addr_local.sin_family = AF_INET; // Protocol Family addr_local.sin_port = htons (PORT); // Port number addr_local.sin_addr.s_addr = htonl (INADDR_ANY); // AutoFill local address memset (addr_local.sin_zero,0,8); // Flush the rest of struct /* Blind a special Port */ if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 ) { printf ("ERROR: Failed to bind Port %d. ",PORT); return (0); } else { printf("OK: Bind the Port %d sucessfully. ",PORT); } /* Listen remote connect/calling */ if(listen(sockfd,BACKLOG) == -1) { printf ("ERROR: Failed to listen Port %d. ", PORT); return (0); } else { printf ("OK: Listening the Port %d sucessfully. ", PORT); } while(1) { sin_size = sizeof(struct sockaddr_in); /* Wait a connection, and obtain a new socket file despriptor for single connection */ if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, (socklen_t *__restrict)&sin_size)) == -1) { printf ("ERROR: Obtain new Socket Despcritor error. "); continue; } else { printf ("OK: Server has got connect from %s. ", inet_ntoa(addr_remote.sin_addr)); } /* Child process */ if(!fork()) {     while (strcmp(revbuf,"exit") != 0)     { //接收数据 memset (revbuf,0,LENGTH); if((num = recv(nsockfd, revbuf, LENGTH, 0))>0) { printf ("OK: Receviced numbytes = %d ", num); revbuf[num] = '