简单易懂 UDP实现客户端通信( 二 )

客户端:UdpClient.c
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> #define PORT8888 struct info{ char buf[100]; int port;}; void *Send(void *arg){ struct info SendBuf = {0}; struct sockaddr_in server_addr; int ret;bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = PF_INET; server_addr.sin_port = PORT; server_addr.sin_addr.s_addr = inet_addr("192.168.0.128");while(1) {scanf("%s %d", SendBuf.buf, &SendBuf.port);ret = sendto(*(int *)arg, &SendBuf, sizeof(SendBuf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));if (ret < 0){perror("sendto");exit(1);}if (!strcmp(SendBuf.buf, "bye")){break;}bzero(&SendBuf, sizeof(SendBuf)); }}void *Recv(void *arg){ struct info RecvBuf = {0}; int length; struct sockaddr_in server_addr; int ret; while (1) {length = sizeof(server_addr);ret = recvfrom(*(int *)arg, &RecvBuf, sizeof(RecvBuf), 0, (struct sockaddr *)&server_addr, &length);if (ret < 0){perror("recvfrom");exit(1);}printf("Recv From Server : %sn", RecvBuf.buf); }}int main(){ int sockfd, ret, length; struct info SendBuf = {0}; pthread_t tid[2]; sockfd = socket(PF_INET, SOCK_DGRAM, 0); if (-1 == sockfd) {perror("sockt");exit(1); } ret = pthread_create(&tid[0], NULL, Send, (void *)&sockfd); if (ret < 0) {perror("pthread_create");exit(1); } ret = pthread_create(&tid[1], NULL, Recv, (void *)&sockfd); if (ret < 0) {perror("pthread_create");exit(1); }pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); close(sockfd); return 0;}
【简单易懂 UDP实现客户端通信】


推荐阅读