C++ 基于UDP的简单通信

服务端

#include “Winsock2.h”
#include “stdio.h”
#pragma   comment(lib,”Ws2_32.lib”)

int main()
{
WORD version;
WSADATA data;
int err;
version=MAKEWORD(1,1);
err=WSAStartup(version,&data);
if(err!=0)
return 0;
if (LOBYTE(data.wVersion)!=1||HIBYTE(data.wVersion)!=1) {
WSACleanup();
return 0;
}
SOCKET sock=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addr;
addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addr.sin_family=AF_INET;
addr.sin_port=htons(6000);
bind(sock,(SOCKADDR*)&addr,sizeof(SOCKADDR));
SOCKADDR_IN addrc;
int len=sizeof(SOCKADDR);
char buf[100];
recvfrom(sock,buf,100,0,(SOCKADDR*)&addr,&len);
printf(“%s
“,buf);

closesocket(sock);
WSACleanup();
return 0;
}

客户端

#include “Winsock2.h”
#include “stdio.h”
int main()
{
WORD version;
WSADATA data;
int err;
version=MAKEWORD(1,1);
err=WSAStartup(version,&data);
if(err!=0)
return 0;
if (LOBYTE(data.wVersion)!=1||HIBYTE(data.wVersion)!=1) {
WSACleanup();
return 0;
}
SOCKET sock=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addr;
addr.sin_addr.S_un.S_addr=inet_addr(“127.0.0.1″);
addr.sin_family=AF_INET;
addr.sin_port=htons(6000);
int len=sizeof(SOCKADDR);
while(1)
{
char buf1[100],buf2[100];
printf(“You are saying:”);
gets(buf1);
sendto(sock,buf1,strlen(buf1)+1,0,(SOCKADDR*)&addr,sizeof(SOCKADDR));
if(buf1[0]==’b'&&buf1[1]==’y'&&buf1[2]==’e')
break;
recvfrom(sock,buf2,100,0,(SOCKADDR *)&addr,&len);
printf(“from server:%s
“,buf2);
}

closesocket(sock);
WSACleanup();

return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>