csocket.cpp

来自「一个简单的http下载程序,用C++在linux下写了一个简单的http下载程序」· C++ 代码 · 共 179 行

CPP
179
字号
#include "CSocket.h"Sock_instance::Sock_instance(string hostname, unsigned port, s_type type)	: _hostname( hostname ), 	 _port( port ),	 _fd( 0 ),	 _state( CONN_ERROR ),	 _type( type ){	_datalen = 0;	_data = new unsigned char[1024*1024];}Sock_instance::~Sock_instance(){	delete[] _data;}bool Sock_instance::Connect(){	if( _type == SERVER_TYPE )	{		cout << "The socket is a server, don't use conncet!" << endl;		return false;	}		struct sockaddr_in peer;	int fd;	bzero( &peer, sizeof(peer) );	peer.sin_family = AF_INET;	struct hostent *hp = gethostbyname( _hostname.c_str() );		if ( hp == NULL )	{		cout << "unknow host: " << _hostname << endl;		return false;	}	peer.sin_addr = *( ( struct in_addr * )hp->h_addr );	peer.sin_port	= htons(_port);	cout << "conncet to " << inet_ntoa(peer.sin_addr)  << ": " << ntohs( peer.sin_port ) << endl;		fd = socket( AF_INET, SOCK_STREAM, 0 );	if ( fd < 0 )	{		cout <<  "socket call failed" << endl;		return false;	}	if( connect( fd, (struct sockaddr *)&peer, sizeof( peer ) ) )	{		cout << errno << "connect failed" << endl;		_state = CONN_ERROR;		close( fd );		return false;	}	_state = CONN_OK;	_fd = fd;		return true;}s_state Sock_instance::state(){	return _state;}int Sock_instance::fd(){	return _fd;}bool Sock_instance::Send(string msg){	if( state() != CONN_OK )	{		cout << "the socket is not ok" << endl;		return false;	}	int rc;	if((rc = send(_fd, msg.c_str(), msg.size(), 0)) == -1)	{		if((errno != EWOULDBLOCK) && (errno != EAGAIN))		{			_state = CONN_ERROR;			return false;		}	}	return true;}int Sock_instance::Receive(){	int rc;	char buf[BUFSIZ];	char *p_buf = buf;	static bool b_readhead = true;	bzero(buf, BUFSIZ);	if((rc = recv( _fd, buf, BUFSIZ - 1, 0 )) < 0 )	{		cout << "recive error" << endl;		_state = CONN_WAIT;		Close();	}	else if( rc == 0 )	{		cout << "server teminated" << endl;		_state = CONN_WAIT;		Close();	}	else	{		//read HTTP head		int ix = 0;		while( b_readhead )		{			// 2 0D 0A just for head end			if( ix >= rc )				break;			if( buf[ix] == 13 && buf[ix+1] == 10 && buf[ix+2] == 13 && buf[ix+3] == 10 )			{				b_readhead = false;				char *p = new char[ix+5];				memset( p, 0, ix+5 );				memcpy( p, buf, ix+5 );				p_buf += ix + 5;				_http_head = p;				delete[] p;				cout << _http_head << endl;				break;			}			ix ++;		}		//copy data to _data		if( ix != 0 && ix < rc )		{			//this buf has head so data begin with buf+ix+4			memcpy( _data+_datalen, buf+ix+4, rc-ix-4 );			_datalen += rc-ix-4;		}		else		{			memcpy( _data+_datalen, buf, rc );			_datalen += rc;			}	}	return rc;}inline void Sock_instance::Close(){	close( _fd );}//string Sock_instance::data() constunsigned char * Sock_instance::data() const{	return _data;}int Sock_instance::datalen() const{	return _datalen;}string Sock_instance::http_head() const{	return _http_head;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?