扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:fs007 来源:vckbase 2007年10月19日
关键字: Visual C++ UDP协议 通讯
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]="\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); } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。