udp伺服器、客戶端之間的相互通訊
之前的版本只能實現udp伺服器之間單發單收,此版本能實現udp伺服器和客戶端之間的相互通訊。
見下面的程式:
udp_server.c
#include #include #include #include #include #include #include #define port 3333
int main()
; if((sockfd = socket(af_inet, sock_dgram, 0)) < 0)
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = af_inet;
server_addr.sin_addr.s_addr = htonl(inaddr_any);
server_addr.sin_port = htons(port);
if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
while(1)
buf[recvbytes] = '\0';
printf("receive from client is %s", buf);
printf("please input:");
fgets(buf1, 1024, stdin);
sendto(sockfd, buf1, 1024, 0, (struct sockaddr *)&client_addr, sizeof(struct sockaddr));
} close(sockfd);
return 0;
}
udp_client.c
#include #include #include #include #include #include #include #define port 3333
int main()
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = af_inet;
//server_addr.sin_addr.s_addr = inet_addr("192.168.1.222");
server_addr.sin_addr.s_addr = htonl(inaddr_any);
server_addr.sin_port = htons(port);
while(1)
memset(buf1, 0, sizeof(buf1));
bzero(&client_addr, sizeof(struct sockaddr_in));
if(recvfrom(sockfd, buf1, sizeof(buf1), 0, (struct sockaddr *)&client_addr, &addrlen) < 0)
printf("receive from server:%s\n", buf1);
} close(sockfd);
return 0;
}
執行結果:
UDP 客戶端伺服器
udp 客戶端 include include include include include define size 100 define ip 127.0.0.1 define port 10086 int main struct sockaddr in addr 建立socket udp so...
UDP實現伺服器和客戶端的通訊
一 服務端 include include include include include include include include include include include include include include include include include include ...
Udp 模擬實現客戶端與伺服器通訊
客戶端模組 include include include std string include close介面 include atoi介面 include 位址結構定義 include 位元組序轉換介面 include 套接字介面 class udpsocket 1.建立套接字 bool soc...