分类: C/C++
2008-03-13 17:41:50
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); }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]="\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); }四、结束语