Visual C++设计UDP协议通讯示例
一、绪言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()
{
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]="";
printf("waiting for message from others-------------
");
if (recvfrom(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
{
printf("Received datagram from %s--%s
",inet_ntoa(from.sin_addr),buffer);
////给cilent发信息
sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&from,fromlen);
}
Sleep(500);
}
closesocket(socket1);
}
udpcilent主要代码:
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]="";
printf("input message
");
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
",buffer);
}
}
closesocket(socket1);
}
四、结束语
UDP通讯比TCP简单了很多,在数据可靠性不是很高的情况下,有使用的价值。