📄 tcpclient.cpp
字号:
/** * * The code to report the error may be a redundance, you can simplify it, but I need them to test * */#include"TcpClient.h"#include<iostream>using namespace std;TcpClient::TcpClient(){ bzero(&Buf,strlen(Buf)); if((Server_host_name=gethostbyname(HOSTNAME))==0){ perror("Error resolving the host! TcpClient Construction\n"); //cerr<<"Error in construction!"<<endl; }else{ Port=PORT; bzero(&Pin,sizeof(Pin)); Pin.sin_family=AF_INET; inet_pton(AF_INET,HOSTNAME,&Pin.sin_addr); //Pin.sin_addr.s_addr=htonl(INADDR_ANY); //Pin.sin_addr.s_addr=((struct in_addr *)(Server_host_name->h_addr))->s_addr; Pin.sin_port=htons(Port); }}TcpClient::TcpClient(int port){ bzero(&Buf,strlen(Buf)); if((Server_host_name=gethostbyname(HOSTNAME))==0){ perror("Error resolving the host! TcpClient Construction\n"); //cerr<<"Error in construction!"<<endl; }else{ Port=port; bzero(&Pin,sizeof(Pin)); Pin.sin_family=AF_INET; inet_pton(AF_INET,HOSTNAME,&Pin.sin_addr); //Pin.sin_addr.s_addr=htonl(INADDR_ANY); //Pin.sin_addr.s_addr=((struct in_addr *)(Server_host_name->h_addr))->s_addr; Pin.sin_port=htons(Port); }}TcpClient::TcpClient(char* hostname,int port){ if((Server_host_name=gethostbyname(hostname))==0){ perror("Error resolving the host! TcpClient Construction\n"); //cerr<<"Error in construction!"<<endl; }else{ Port=port; bzero(&Pin,sizeof(Pin)); Pin.sin_family=AF_INET; inet_pton(AF_INET,hostname,&Pin.sin_addr); //Pin.sin_addr.s_addr=htonl(INADDR_ANY); //Pin.sin_addr.s_addr=((struct in_addr *)(Server_host_name->h_addr))->s_addr; Pin.sin_port=htons(Port); }}int TcpClient::InitTcpClient(){ int sd; if((sd=(Socket_descriptor=socket(AF_INET,SOCK_STREAM,0)))==-1){ perror("Error opening socket\n"); return -1; } return sd;}int TcpClient::Connect(){ if(connect(Socket_descriptor,(sockaddr *)&Pin,sizeof(Pin))==-1){ perror("Error connecting to socket\n"); return -1; } //cerr<<"Connected"<<endl; return 1;}int TcpClient::Send(T* buf){ strcpy(Buf,buf); Buf[strlen(Buf)]=0; int s=send(Socket_descriptor,Buf,strlen(Buf),0);//cerr<<"Send:"<<Buf<<endl; if(s==-1){ perror("send"); } return s;}int TcpClient::Recv(T* buf){ int r=recv(Socket_descriptor,buf,BUFSIZE,0); if(r==-1){ perror("recv"); } return r;}int TcpClient::Recvc(T* ch){ int r=recv(Socket_descriptor,ch,1,0); if(r==-1){ perror("recvc"); } return r;}void TcpClient::Close(){ close(Socket_descriptor);}int TcpClient::getSockfd() const{ return Socket_descriptor;}int TcpClient::getPort() const{ return Port;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -