TA的每日心情 | 开心 2024-10-25 14:50 |
---|
签到天数: 1071 天 连续签到: 1 天 [LV.10]以坛为家III
|
这篇来测试下在开发板上搭建tcp server测试。
一、测试程序
使用socket的方式来测试。
- <font size="3">#include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #define SERVER_NET_PORT 8866
- int main(void)
- {
- struct sockaddr_in server_addr = {0};
- struct sockaddr_in client_addr = {0};
- char ip_str[20] = {0};
- int sockfd, connfd;
- int addrlen = sizeof(client_addr);
- char recvbuf[512];
- int ret;
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (0 > sockfd)
- {
- perror("socket error");
- exit(EXIT_FAILURE);
- }
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
- server_addr.sin_port = htons(SERVER_NET_PORT);
- ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
- if (0 > ret)
- {
- perror("bind error");
- close(sockfd);
- exit(EXIT_FAILURE);
- }
- ret = listen(sockfd, 50);
- if (0 > ret)
- {
- perror("listen error");
- close(sockfd);
- exit(EXIT_FAILURE);
- }
- connfd = accept(sockfd, (struct sockaddr *)&client_addr, &addrlen);
- if (0 > connfd)
- {
- perror("accept error");
- close(sockfd);
- exit(EXIT_FAILURE);
- }
- printf("client connect...\n");
- inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_str, sizeof(ip_str));
- printf("client ip addr: %s\n", ip_str);
- printf("client port: %d\n", client_addr.sin_port);
- for ( ; ; )
- {
- memset(recvbuf, 0x0, sizeof(recvbuf));
- ret = recv(connfd, recvbuf, sizeof(recvbuf), 0);
- if(0 >= ret)
- {
- perror("recv error");
- close(connfd);
- break;
- }
- printf("from client: %s\n", recvbuf);
- if (0 == strncmp("exit", recvbuf, 4))
- {
- printf("server exit...\n");
- close(connfd);
- break;
- }
- }
- close(sockfd);
- exit(EXIT_SUCCESS);
- }
- </font>
复制代码
二、编译程序
使用开发板的编译工具来编译测试程序
2.1、编译命令
root@ubuntu:/opt/work/test/net# aarch64-linux-gnu-gcc socket_server.c -o socket_server
2.2、看编译后的文件
2.3、复制文件到开发板
执行命令:
root@ubuntu:/opt/work/test/net# scp socket_server root@192.168.1.46:/opt/
三、运行程序
在开发板上执行命令:root@myd-jd9x:/opt# ./socket_server
TCP客户端与服务器之间数据传输
|
|