一、緒言
udp是一種面向非連接,不可靠的通訊協議,相對於tcp來說,雖然可靠性不及,但傳輸效率較高。所以在網絡上仍有很大的用途。這幾日需要了解下udp通訊的過程,上網發現這方面的資料還挺少。於是仔細的翻找了下msdn,基本上搞清楚了udp通訊的過程。做了一個測試的例子。希望對大家有幫助。
二、udp的通訊過程
server端: open a socket(socket)--->name the socket(bind)--->send and receive data(sendto recvfrom)--->close socket(closesocket)
client端: open a socket(socket)---------------------------->send and receive data(sendto recvfrom)--->close socket(closesocket)
server端無需listen,client端無需connect,因此udp中server和client的區別相對較模糊。只要調用sendto和recvfrom就可以給指定的地址收發數據,但並不保證收發的數據的完整性和可靠性。
三、示例
udpserver主要代碼:
void main()
udpcilent主要代碼:
{
SOCKET socket1;
InitWinsock();
struct sockaddr_in local;
struct sockaddr_in from;
int fromlen =sizeof(from);
local.sin_family=AF_INET;
local.sin_port=htons(1000); ///監聽端口
local.sin_addr.s_addr=INADDR_ANY; ///本機
socket1=socket(AF_INET,SOCK_DGRAM,0);
bind(socket1,(struct sockaddr*)&local,sizeof local);
while (1)
{
char buffer[1024]="\0";
printf("waiting for message from others-------------\n");
if (recvfrom(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer);
////給cilent發信息
sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&from,fromlen);
}
Sleep(500);
}
closesocket(socket1);
}void main()
{
SOCKET socket1;
InitWinsock();
struct sockaddr_in server;
int len =sizeof(server);
server.sin_family=AF_INET;
server.sin_port=htons(1000); ///server的監聽端口
server.sin_addr.s_addr=inet_addr("168.168.0.10"); ///server的地址
socket1=socket(AF_INET,SOCK_DGRAM,0);
while (1)
{
char buffer[1024]="\0";
printf("input message\n");
scanf("%s",buffer);
if (strcmp(buffer,"bye")==0)
break;
if (sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&server,len)!=SOCKET_ERROR)
{
if (recvfrom(socket1,
buffer,
sizeof buffer,
0,
(struct sockaddr*)&server,&len) != SOCKET_ERROR)
printf("rece from server:%s\n",buffer);
}
}
closesocket(socket1);
}
四、結束語
udp通訊比tcp簡單了很多,在數據可靠性不是很高的情況下,有使用的價值。
本文配套源碼