C語言實現(xiàn)UDP通信
UDP通信
UDP是一種無連接的盡最大努力交付的不可靠連接,通信之前無需先建立連接,自然而然,通信之后也就無需再釋放連接。
通信的套接字
UDP所采用的通信接口與前面講過的TCP通信接口相同,只是沒有建立連接這一步。
socket()用來創(chuàng)建套接字,使用 udp 協(xié)議時,選擇數(shù)據(jù)報服務(wù) SOCK_DGRAM。sendto()用來發(fā)送數(shù)據(jù),由于 UDP 是無連接的,每次發(fā)送數(shù)據(jù)都需要指定對端的地址(IP 和端口)。recvfrom()接收數(shù)據(jù),每次都需要傳給該方法一個地址結(jié)構(gòu)來存放發(fā)送端的地址。
recvfrom()可以接收所有客戶端發(fā)送給當(dāng)前應(yīng)用程序的數(shù)據(jù),并不是只能接收某一個客戶端的數(shù)據(jù)
通信流程


通信過程
客戶端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
?? ?int sockfd = socket(AF_INET,SOCK_DGRAM,0);
?? ?assert( sockfd != -1 );
?? ?struct sockaddr_in saddr;
?? ?memset(&saddr,0,sizeof(saddr));
?? ?saddr.sin_family = AF_INET;
?? ?saddr.sin_port = htons(6000);
?? ?saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
?? ?while( 1 )
?? ?{
?? ?char buff[128] = {0};
?? ?printf("input:\n");
?? ?fgets(buff,128,stdin);
?? ?if ( strncmp(buff,"end",3) == 0 )
?? ?{
?? ??? ?break;
?? ?}
?? ?sendto(sockfd,buff,strlen(buff),0,(struct ckaddr*)&saddr,sizeof(saddr));
?? ?memset(buff,0,128);
?? ?int len = sizeof(saddr);
?? ?recvfrom(sockfd,buff,127,0,(struct sockaddr*)&saddr,&len);
?? ?printf("buff=%s\n",buff);
?? ?}
?? ?close(sockfd);
}服務(wù)器端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
?? ?int sockfd = socket(AF_INET,SOCK_DGRAM,0);
?? ?assert( sockfd != -1 );
?? ?struct sockaddr_in saddr,caddr;
?? ?memset(&saddr,0,sizeof(saddr));
?? ?saddr.sin_family = AF_INET;
?? ?saddr.sin_port = htons(6000);
?? ?saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
?? ?int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
?? ?assert( res != -1 );
?? ?while( 1 )
?? ?{
?? ??? ?int len = sizeof(caddr);
?? ??? ?char buff[128] = {0};
?? ??? ?recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr,&len);
?? ??? ?printf("ip:%s,port:%d,buff=%s\n",inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port),buff );
?? ??? ?sendto(sockfd,"ok",2,0,(struct sockaddr*)&caddr,sizeof(caddr));
?? ?}
?? ?close(sockfd);
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Win10下最新版CLion(2020.1.3)安裝及環(huán)境配置教程詳解
這篇文章主要介紹了Win10下最新版CLion(2020.1.3)安裝及環(huán)境配置,CLion 是 JetBrains 推出的全新的 C/C++ 跨平臺集成開發(fā)環(huán)境,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-08-08
C++實現(xiàn)LeetCode(170.兩數(shù)之和之三 - 數(shù)據(jù)結(jié)構(gòu)設(shè)計)
這篇文章主要介紹了C++實現(xiàn)LeetCode(170.兩數(shù)之和之三 - 數(shù)據(jù)結(jié)構(gòu)設(shè)計),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C++ Qt開發(fā)之CheckBox多選框組件的用法詳解
Qt是一個跨平臺C++圖形界面開發(fā)庫,利用Qt可以快速開發(fā)跨平臺窗體應(yīng)用程序,在Qt中我們可以通過拖拽的方式將不同組件放到指定的位置,實現(xiàn)圖形化開發(fā)極大的方便了開發(fā)效率,本章將重點介紹CheckBox單行輸入框組件的使用方法,需要的朋友可以參考下2023-12-12

