歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Socket編程獲取服務器時間

Socket編程獲取服務器時間

日期:2017/3/1 9:58:01   编辑:Linux編程

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

1. 客戶端

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

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

連接服務器;

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

#include<string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <sys/errno.h>
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
const int MAXLINE=1024;
int main(int argc,char** argv)
{
int sockfd,n;
char recvline[MAXLINE+1];
struct sockaddr_in servaddr;
if(argc!=2)
{
cout<<"usage: a.out<IPaddress"<<endl;
exit(0);
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
cout<<"socket error"<<endl;
exit(0);
}
memset(&servaddr,0, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(8080);//將無符號短整型數值轉換為網絡字節序,即將數值的高位字節存放到內存中的低位字節0X1234變為0X3412
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0)//將ip地址在“點分十進制”和整數之間轉換
{
cout<<"inet_ptons error"<<endl;
exit(0);
}
if(connect(sockfd,(sockaddr*)&servaddr,sizeof(servaddr))<0)
{
cout<<"connect error"<<endl;
exit(0);
}
while((n=read(sockfd,recvline,MAXLINE))>0)
{
recvline[n]=0;
if(fputs(recvline,stdout)==EOF)
{
cout<<"fputs error"<<endl;
exit(0);
}
}
if(n<0)
{
cout<<"read error"<<endl;
exit(0);
}
exit(0);
}

Copyright © Linux教程網 All Rights Reserved