客戶端向服務器端發送請求,服務器收到請求做相應的處理,將處理結果傳回客戶端。下面採用TCP協議實現服務器和客戶端之間的連接。
1. 客戶端
約定雙方的傳輸協議(UDP或者TCP),根據傳輸協議創建socket;
服務器的IP地址和端口號;
連接服務器;
獲取服務器傳遞回來的數據。
- <span style="font-size:18px;"><strong>#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);
- } </strong></span>
2. 服務器
約定雙方的傳輸協議(UDP或者TCP),根據傳輸協議創建socket;
將地址和端口綁定到socket;
對端口進行偵聽,直到偵聽到有連接信息;
接收連接,然後將數據寫回連接中。
將地址和端口綁定到socket
- <span style="font-size:18px;"><strong>#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>
- #include<errno.h>
- using namespace std;
- const int MAXLINE=1024;
- int main(int argc,char **argv)
- {
- int listenfd,connfd;
- struct sockaddr_in servaddr;
- char buff[MAXLINE];
- time_t ticks;
- listenfd=socket(AF_INET,SOCK_STREAM,0);//建立socket
- if(listenfd<0)
- {
- cout<<"socket error "<<strerror(errno)<<endl;
- exit(0);
- }
- memset(&servaddr,0, sizeof(servaddr));
- servaddr.sin_family=AF_INET;
- servaddr.sin_port=htons(8080);
- servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
- int bindfd=bind(listenfd,(sockaddr*)&servaddr,sizeof(servaddr));//將地址和端口綁定到socket
- if(bindfd<0)
- {
- cout<<"bind error"<<bindfd<<endl;
- exit(0);
- }
- listen(listenfd,MAXLINE);//監聽連接,一直阻塞,直到有連接出現
- while(1)
- {
- connfd=accept(listenfd,(sockaddr*)NULL,NULL);//接收連接傳遞的數據
- ticks=time(NULL);
- snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
- cout<<strlen(buff)<<endl;
- write(connfd,buff,strlen(buff));//將傳遞的數據寫回到socket中
- close(connfd);
- }
- return 0;
- } </strong></span>
- 上一篇 帶外數據
- 下一篇 linux 開機自啓動設置 inittab 詳解