C++ Server and Client

 

==================  Server  ================== 

#include
#include

#pragma comment(lib,"ws2_32.lib")

int main(void)

{
     WSADATA wsa;
     WSAStartup(MAKEWORD(2,2),&wsa);

     struct sockaddr_in addr_server;
     addr_server.sin_family = AF_INET;
     addr_server.sin_port = htons(8000);
     addr_server.sin_addr.s_addr = INADDR_ANY;

     SOCKET serversocket = socket(AF_INET,SOCK_DGRAM,0);

     bind(serversocket,(struct sockaddr*)&addr_server,sizeof(addr_server));
 
     struct sockaddr_in addr_from;

     int  fromlen = sizeof(addr_from);
 
     while(1)
    {
          char frombuff[1024] = "\0";


          printf("\n********** 等待客户端输入信息 **********\n");

          if(recvfrom(serversocket,frombuff,sizeof(frombuff),0,(struct sockaddr*)&addr_from,&fromlen) == SOCKET_ERROR)
          {
               printf("服务端接受有错误!!");
          }

         printf("客户端输入的是:%s\n",frombuff);
       
         //Sleep(5000);

         if(sendto(serversocket,frombuff,sizeof(frombuff),0,(struct sockaddr*)&addr_from,fromlen) == SOCKET_ERROR)
        {
            printf("服务端发送错误!!");
        }
   }

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

 

 

 

==================  Client  ================== 

#include
#include
#include

#pragma comment(lib,"ws2_32.lib")

int main(void)
{
     WSADATA wsa;
     WSAStartup(MAKEWORD(2,2),&wsa);

     SOCKET mySocket;
     mySocket = socket(AF_INET,SOCK_DGRAM,0);

     struct sockaddr_in addr;
     addr.sin_family = AF_INET;
     //addr.sin_addr.s_addr = inet_addr("192.168.1.1");

     addr.sin_addr.s_addr = htonl(INADDR_ANY); //获取本机IP地址
     addr.sin_port = htons(8000);
     int len  = sizeof(addr);

     while(1)
     {
          printf("\n********** NEW START **********\n");
          printf("请输入一段字符给服务器:\n");
          char buff[1024] = "\0";
          gets(buff);
  
          //LARGE_INTEGER t1,t2,feq;
          //QueryPerformanceFrequency(&feq);//每秒跳动次数

          if(sendto(mySocket,buff,sizeof(buff),0,(struct sockaddr *)&addr,len) == SOCKET_ERROR)
          {
               printf("发送错误!!!");
          }
          //QueryPerformanceCounter(&t1);//测前跳动次数

          if(recvfrom(mySocket,buff,sizeof(buff),0,(struct sockaddr*)&addr,&len) == SOCKET_ERROR)
          {
               printf("接受错误!!!");
          }
          //QueryPerformanceCounter(&t2);//测后跳动次数
  
          printf("从服务端返回:%s\n",buff);
          //printf("--->>时间延迟:%f秒\n",((double)t2.QuadPart-(double)t1.QuadPart)/((double)feq.QuadPart));
 }
  
     closesocket(mySocket);
     WSACleanup();
     return 0;
}

 

你可能感兴趣的:(socket)