Purple Pi开发板的特色是路由器,今天从头书写一个tcp通信的实例。
1、查找资料,搜索arm-linux tcp通信。网上的资料非常多,这里学习了https://blog.csdn.net/yishuicanhong/article/details/80639957这位大佬的作品。
2、建立sever服务端,先定义服务端端口:3861,最大连入端户端数量:10,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <pthread.h>
#define SERVER_PORT 3861
#define LISENT_NUM 10
int main(int argc, char * argv[])
{
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];
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));
while (1)
{
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);
if(recv(cfd, buff, sizeof(buff), 0) == -1)
{
perror("recv");
exit(-1);
}
printf("receive: %s\n", buff);
}
return 0;
}
编译后上传给开发板:
3、编写客户端连接tcp_client.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/wait.h>
#define SERVER_PORT 2828
int main(int argc, char * argv[])
{
int sockfd, len;
char buff[1024];
struct sockaddr_in clientAddr;
struct sockaddr_in serverAddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(-1);
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("192.168.43.134");
serverAddr.sin_port = htons(SERVER_PORT);
printf("connect server %s: %d\n", inet_ntoa(serverAddr.sin_addr), SERVER_PORT);
if(connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)) == -1)
{
perror("connect");
exit(-1);
}
printf("connect success!\n");
while (1)
{
send(sockfd, "hello Purple Pi client", 6, 0);
len = recv(sockfd, buff, sizeof(buff), 0);
if(len == -1)
{
break;
}
printf("receive: %s\n",buff);
usleep(1000*1000);
}
printf("client exit!\n");
close(sockfd);
return 0;
}
同样编译上传给开发板:
4、运行server:
【总结】Purple Pi开发板 在linux socket通信方面非常友好。
更多回帖