【完美体育·(中国)手机网页版MYD-Y6ULX-V2开发板】创建TCP通信
文章来源: 发布日期:2023.2.28 浏览次数:656 次 |
由评测者“华仔stm32”提供。
在上个驱动ssd1306的基础上,新增tcp_server的通信。
修改main.c主程序如下:
#include#include #include #include #include #include #include #include #include #include #include #include #include "ssd1306.h" #define SERVER_PORT 3861 #define LISENT_NUM 10 int main() { int sfd, cfd; struct sockaddr_in clientaddr; struct sockaddr_in serverAddr; char buff[1024]; int size = sizeof(struct sockaddr); pthread_t client_thread[LISENT_NUM]; SSD1306_init(); SSD1306_clearDisplay(); SSD1306_setBrightness(255); SSD1306_setPageMode(); SSD1306_setTextXY(0,0); SSD1306_putString("HELLO MYD-Y6ULX!"); SSD1306_setTextXY(1,0); SSD1306_putString("SSD1306 DEMO"); SSD1306_setTextXY(2,0); SSD1306_putString("2022-11-07"); if((sfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(-1); } memset(&serverAddr, 0, sizeof(struct sockaddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(SERVER_PORT); if (bind(sfd, (struct sockaddr*)&serverAddr, sizeof(struct sockaddr)) == -1) { perror("bind"); close(sfd); exit(-1); } if(listen(sfd, LISENT_NUM) == -1) { perror("listen"); close(sfd); exit(-1); } printf("#@ listen SERVER_PORT %d\n", SERVER_PORT); printf("main: server waiting connect...\n"); if ((cfd = accept(sfd, (struct sockaddr *)&clientaddr, (socklen_t*)&size)) == -1) { perror("accept"); close(sfd); return 0; } printf("client (ip = %s : SERVER_PORT = %d) connect success\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); usleep(1000*10); if (send(cfd, "hello Purple Pi", 6, MSG_NOSIGNAL) == -1) { perror("send"); exit(-1); } printf("send: hello Purple Pi\n"); usleep(1000*10); while (1) { if(recv(cfd, buff, sizeof(buff), 0) == -1) { perror("recv"); exit(-1); } printf("receive: %s\n", buff); SSD1306_setTextXY(4,0); SSD1306_putString(buff); } close(ssd1306_i2c_devfd); return 0; }
这样就创建了一个端口为3861的TCP服务端:
编译通过后,上传开发板,运行:
用tcp测试工具连接上开发板:
客户端发送信息:hello Y6ULX,在OLED屏上显示接收到的信息:
到此tcp_server通信实验调试通过,但是这个只是单线程的,下一期修改为同时可以接受多个客户端案例。