歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> UNIX網絡編程初探---獲取服務器時間

UNIX網絡編程初探---獲取服務器時間

日期:2017/3/1 10:24:41   编辑:Linux編程

客戶端向服務器端發送請求,服務器收到請求做相應的處理,將處理結果傳回客戶端。下面采用TCP協議實現服務器和客戶端之間的連接。

1. 客戶端

約定雙方的傳輸協議(UDP或者TCP),根據傳輸協議創建socket;

服務器的IP地址和端口號;

連接服務器;

獲取服務器傳遞回來的數據。

  1. #include<string.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <sys/time.h>
  5. #include <time.h>
  6. #include <fcntl.h>
  7. #include<netinet/in.h>
  8. #include<arpa/inet.h>
  9. #include <sys/errno.h>
  10. #include<iostream>
  11. #include<stdlib.h>
  12. #include<stdio.h>
  13. using namespace std;
  14. const int MAXLINE=1024;
  15. int main(int argc,char** argv)
  16. {
  17. int sockfd,n;
  18. char recvline[MAXLINE+1];
  19. struct sockaddr_in servaddr;
  20. if(argc!=2)
  21. {
  22. cout<<"usage: a.out<IPaddress"<<endl;
  23. exit(0);
  24. }
  25. sockfd=socket(AF_INET,SOCK_STREAM,0);
  26. if(sockfd<0)
  27. {
  28. cout<<"socket error"<<endl;
  29. exit(0);
  30. }
  31. memset(&servaddr,0, sizeof(servaddr));
  32. servaddr.sin_family=AF_INET;
  33. servaddr.sin_port=htons(8080);//將無符號短整型數值轉換為網絡字節序,即將數值的高位字節存放到內存中的低位字節0X1234變為0X3412
  34. if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0)//將ip地址在“點分十進制”和整數之間轉換
  35. {
  36. cout<<"inet_ptons error"<<endl;
  37. exit(0);
  38. }
  39. if(connect(sockfd,(sockaddr*)&servaddr,sizeof(servaddr))<0)
  40. {
  41. cout<<"connect error"<<endl;
  42. exit(0);
  43. }
  44. while((n=read(sockfd,recvline,MAXLINE))>0)
  45. {
  46. recvline[n]=0;
  47. if(fputs(recvline,stdout)==EOF)
  48. {
  49. cout<<"fputs error"<<endl;
  50. exit(0);
  51. }
  52. }
  53. if(n<0)
  54. {
  55. cout<<"read error"<<endl;
  56. exit(0);
  57. }
  58. exit(0);
  59. }
Copyright © Linux教程網 All Rights Reserved