⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 client_udp.cpp

📁 udp 的连接实例
💻 CPP
字号:
#include "winsock2.h"
#include <stdio.h> 
#include "time.h"
#include "stddef.h"
#include <iostream>
using namespace std;

int main() 
{
//-----------------------------------------------
//defined 
   WSADATA              wsaData;
   SOCKET               mySocket;
   SOCKADDR_IN          serverAddr; 
   int                  Port=27015;
   char                 recbuf[40];
   char                 ip[20];
   char					request[5]={'t','i','m','e','?'};
//-----------------------------------------------
// Initialize Winsock
   cout<<"Input server's IP:\n";
   cin>>ip;
   WSAStartup(MAKEWORD(2,2), &wsaData);
   
//-----------------------------------------------
// Create a socket   
      mySocket=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);  
      serverAddr.sin_family = AF_INET;
      serverAddr.sin_port = htons(Port);    
      serverAddr.sin_addr.s_addr = inet_addr(ip);
//----------------------------------------------- 
//Send the request and check the server	   
      if(sendto(mySocket,request,strlen(request),0,(SOCKADDR *) &serverAddr,sizeof(serverAddr))==SOCKER_ERROR); 
	  {
	  cout<<"the client can not send request!"<<endl;
		return 0;
	  };
//-----------------------------------------------
//Receive the time_char[] from the server	  
		  printf("connected.\n");
		  int len=recv( mySocket, recbuf, 40, 0);
//-----------------------------------------------
//Show the time of the server
		  printf("server time: %s \n",recbuf);		  
//-----------------------------------------------
//Show the time of the client	
		  struct tm *str1;
		  time_t tnow;
		  tnow=time(0);
		  str1=localtime(&tnow);
		  printf("local time:  %s \n",asctime(str1));	  
//-----------------------------------------------
//closed	    
      closesocket(mySocket);  
      WSACleanup();
	  return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -