TCP SOCKET 类的实现

来源:互联网 发布:东莞企石淘宝培训 编辑:程序博客网 时间:2024/06/02 18:36

//TcpSocket.h#ifndef _TCPSOCKET_H__#define _TCPSOCKET_H__#include <netinet/in.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/socket.h>#include <sys/wait.h>#include <sys/time.h>#include <netdb.h>      #include <pthread.h>#include <arpa/inet.h>#include <signal.h>#include <errno.h>        #include <unistd.h>       #include <dirent.h>       #include <limits.h>#include <getopt.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <ctype.h>#include <stddef.h>#include<string>#include<iostream>using namespace std;class CTcpSocket{public:CTcpSocket(void);virtual ~CTcpSocket(){NULL;};int tcpCreate(const int port,const char* pszIpStr);int tcpBind();int tcpListen(const int iLisNum);int tcpAccept();int tcpConnect();int tcpSend(int iSendFd,const char* pszSenBuf,int iSenBufLen);int tcpRecv(int iRecFd,char*pszRecBuf,int iRecBufLen);void tcpClose();public:    int iTcpSock;private: sockaddr_in TcpAddr; socklen_t iAddLen;};#endif  //TcpSocket.cpp#include"TcpSocket.h"CTcpSocket::CTcpSocket(void){  iTcpSock=0;}int CTcpSocket::tcpCreate(const int port,const char* pszIpStr){  bzero(&TcpAddr,sizeof(TcpAddr));  TcpAddr.sin_family=AF_INET;if(pszIpStr!=NULL){TcpAddr.sin_addr.s_addr=inet_addr(pszIpStr);}else{TcpAddr.sin_addr.s_addr=htonl(INADDR_ANY);}TcpAddr.sin_port=htons(port);iAddLen=sizeof(TcpAddr);iTcpSock=socket(AF_INET,SOCK_STREAM,0);return iTcpSock;}int  CTcpSocket::tcpBind(){int iBind=0;iBind=bind(iTcpSock,(struct sockaddr*)&TcpAddr,sizeof(TcpAddr));if(-1==iBind) { cout<<"bind error"<<endl;exit(-1);}return iBind;}int CTcpSocket::tcpListen(const int iLisNUm){return listen(iTcpSock,iLisNUm);}int CTcpSocket::tcpAccept(){ int iAccpet=0; iAccpet=accept(iTcpSock,(struct sockaddr*)&TcpAddr,&iAddLen); if(-1==iAccpet) { cout<<"accpet error!"<<endl; exit(1);}return iAccpet;}int CTcpSocket::tcpConnect(){int iConnect=connect(iTcpSock,(struct sockaddr*)&TcpAddr,iAddLen);if(-1==iConnect){cout<<"connect error"<<endl;exit(-1);}return iConnect;} int CTcpSocket::tcpSend(int iSendFd,const char*pszSenBuf,int iSenBufLen){int iSendNum=0;iSendNum=write(iSendFd,pszSenBuf,iSenBufLen);if(iSendNum!=iSenBufLen)cout<<"sendNum!=senBufLen"<<endl;return iSendNum;}int CTcpSocket::tcpRecv(int iRecFd,char* pszRecBuf,int iRecBufLen){int iRecNum=0;iRecNum=read(iRecFd,pszRecBuf,iRecBufLen);return iRecNum;}void CTcpSocket::tcpClose(){close(iTcpSock);}