客户端程序代码如下:
#pragma comment(lib,"ws2_32.lib") #include<winsock2.h> #include<stdio.h> BOOL InitWinsock(); void main() { SOCKET socket1; InitWinsock(); struct sockaddr_in server; int len=sizeof(server); server.sin_family=AF_INET; server.sin_port=htons(1000); //Server的监听端口为1000 server.sin_addr.s_addr=inet_addr("192.168.0.199"); 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); } BOOL InitWinsock() { int Error; WORD VersionRequested; WSADATA WsaData; VersionRequested=MAKEWORD(2,2); Error=WSAStartup(VersionRequested,&WsaData); if(Error!=0) { return FALSE; } else { if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2) { WSACleanup(); return FALSE; } } return TRUE; }
//htons()的功能:将一个无符号短整型数值转换为网络字节序,即大端模式(big-endian)
服务端程序代码:
#pragma comment(lib,"ws2_32.lib") #include<winsock2.h> #include<stdio.h> BOOL InitWinsock(); 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-------------"); 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);
//给Client发信息 sendto(socket1,strcat(buffer,"hello"),sizeof(strcat(buffer,"hello")),0,(struct sockaddr*)&from,fromlen); printf("%s",buffer); } Sleep(500); } closesocket(socket1); } BOOL InitWinsock() { int Error; WORD VersionRequested; WSADATA WsaData; VersionRequested=MAKEWORD(2,2); Error=WSAStartup(VersionRequested,&WsaData); if(Error!=0) { return FALSE; } else { if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2) { WSACleanup(); return FALSE; } } return TRUE; }