原文地址:https://www.xuebuyuan.com/2181604.html
/*Socket基础 UDP * A与B发送消息 * */ #include<stdio.h> #include<taskLib.h> #include<unistd.h> #include<sockLib.h> #include<netinet/in.h> #include<inetLib.h> #include<string.h> #define TASK_PRIORITY_A 130 #define TASK_PRIORITY_B 130 #define STACK_SIZE 225 #define PORT 3733 int taskId_A, taskId_B; /*定义两个Task*/ void taskA(void); void taskB(void); /*服务器ip地址*/ char ip[]="127.0.0.1"; /*服务端地址与客户端地址*/ struct sockaddr_in serAddr, cliAddr; int len=sizeof(struct sockaddr_in); int taskDemo() { /*创建任务:taskSpawn创建并激活任务*/ taskId_A=taskSpawn("taskA", TASK_PRIORITY_A, VX_FP_TASK, STACK_SIZE, (FUNCPTR)taskA, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); taskId_B=taskSpawn("taskB", TASK_PRIORITY_B, VX_FP_TASK, STACK_SIZE, (FUNCPTR)taskB, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (taskId_A==ERROR) printf("taskA taskSpawn() failed!\n"); if (taskId_B==ERROR) printf("taskB taskSpawn() failed!\n"); } /*服务端*/ void taskA() { int sockFd, newFd, rLen; char msg[]="hello", buf[255]; /*创建套接字*/ sockFd=socket(AF_INET,SOCK_DGRAM,0); /**************************************************************** * 设置套接字要绑定的网络地址,通过对结构体struct sockaddr_in seraddr赋值*/ serAddr.sin_family=AF_INET;/*协议族 为ip协议族*/ serAddr.sin_port=PORT;/*端口号*/ inet_aton(ip, &(serAddr.sin_addr));/*将ip地址转为32位整数*/ memset(serAddr.sin_zero, 0, 8); /****************************************************************/ /*socket与地址绑定*/ if (bind(sockFd, (struct sockaddr*)&serAddr, len)==OK) printf("Connected!\n"); /*接收数据*/ recvfrom(sockFd, buf, sizeof(buf), 0, (struct sockaddr*)&cliAddr, &len); printf("[Server]Get message:%s\n", buf); sendto(sockFd, msg, sizeof(msg), 0, (struct sockaddr*)&cliAddr, len); printf("[Server]Send msg to client!\n"); } /*客户端*/ void taskB() { int sockFd, rLen; char buf[255], msg[]="This is client!"; /*创建socket*/ sockFd=socket(AF_INET,SOCK_DGRAM,0); /*连接*/ sendto(sockFd, msg, sizeof(msg), 0, (struct sockaddr*)&serAddr, len); printf("[Client]Send msg to server!\n"); recvfrom(sockFd, buf, sizeof(buf), 0, (struct sockaddr*)&serAddr, &len); printf("[Client]Get message:%s\n", buf); }