"); //-->
char message[]= "hello rt-thread server!"; #define BUFSZ 1024 void tcpclient(void) { int ret; char *recv_data; struct hostent *host; int sock,bytes_recived; struct sockaddr_in server_addr; char url[] = "192.168.1.45"; int port = 5000; host = gethostbyname(url); recv_data = rt_malloc(BUFSZ); sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0) { rt_kprintf("sock create failed"); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr = *((struct in_addr *)host->h_addr); if(connect(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1) { rt_kprintf("connect fail !\n"); closesocket(sock); return; } else { rt_kprintf("connect successful\n"); send(sock,message,sizeof(message),0); } while(1) { bytes_recived = recv(sock,recv_data,BUFSZ -1,0); if(bytes_recived < 0) { closesocket(sock); rt_kprintf("\nreceived error,close the socket.\r\n"); rt_free(recv_data); break; } else if(bytes_recived == 0) { closesocket(sock); rt_kprintf("\n received error,close the socket .\r\n"); rt_free(recv_data); break; } recv_data[bytes_received] = '\0'; if(strncmp(recv_data,"q",1) == 0 || strncmp(recv_data,"Q",1)) { closesocket(sock); rt_kprintf("\n got a 'q' or 'Q',close the socket.\r\n“); rt_free(recv_data); break; } else { rt_kprintf("\n Received data = %s ",recv_data); } ret =send(sock, send_data, strlen(send_data), 0); if(ret < 0) { closesocket(sock); rt_kprintf("\n send error,close the socket.\r\n"); rt_free(recv_data); break; } else if (ret == 0) { rt_kprintf("send warning ,send function return \r\n"); } } }
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。