Linux Socket編程擷取伺服器時間

來源:互聯網
上載者:User

用戶端向伺服器端發送請求,伺服器收到請求做相應的處理,將處理結果傳回用戶端。下面採用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);    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.