All pastes #813902 Raw Edit

Untitled

public text v1 · immutable
·published 2007-12-12 21:39 UTC
rendered paste body
#include "TCPSocket.h"

TCPSocket::TCPSocket()
{
	throw TCPSocketException("The constructor of the TCPSocket class require 2 parameters");
}

TCPSocket::TCPSocket(char * adresse, int port)
{
	FD_ZERO(&set);
	memset(&sin,0,sizeof(sockaddr_in));
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;
	
	struct hostent * host_ip;
	
	#ifdef WIN32  
	WSADATA Data; 
	WSAStartup (MAKEWORD (2, 2), &Data); 
	#endif
	
	sin.sin_family = AF_INET; 
  	sin.sin_port = htons(port); 
	
	/* Creation de la socket */
	sock = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  	if (sock < 0)
  	{ 
		throw TCPSocketException("Error creating the socket");
    } 

	sin.sin_addr.s_addr = inet_addr(adresse);
	if(sin.sin_addr.s_addr == -1)
	{
		host_ip = gethostbyname(adresse);
		if(host_ip == NULL)
		{
			throw TCPSocketException("Error resolving domain name");
		}
		else
		{
			memcpy(&sin.sin_addr.s_addr, host_ip->h_addr, host_ip->h_length);
		}
	}	
}

TCPSocket::~TCPSocket()
{
	if(sock > 0)
		close(sock);
}

bool TCPSocket::connect()
{
	int n;
	n = ::connect(sock, (sockaddr *)&sin, sizeof(sockaddr_in));
	if(n >= 0)
	{
		FD_ZERO(&set);
		FD_SET(sock, &set);
  		return true;
  	}
  	else
  		return false;
}

void TCPSocket::disconnect()
{
	if(sock > 0)
	{
		FD_CLR(sock, &set);
		close(sock);
	}
}

bool TCPSocket::send(char * msg)
{
	if(::send(sock,msg,strlen(msg), 0)>0)
		return true;
	else
		return false;
}

bool TCPSocket::readable()
{
	fd_set temp_set = set;
	if(select(sock+1, &temp_set, 0, 0,&timeout) > 0)
		return true;
	else
		return false;
}

int TCPSocket::recv(char * buffer, int maxLength)
{
		
int taille = ::recv(sock, buffer, maxLength, 0);
		buffer[taille] = 0;
		return taille;
}