コード例 #1
0
ファイル: HTTPInputStream.cpp プロジェクト: Iiridayn/sample
int HTTPInputStream::Read() {
  if (!IsOpen()) {
    throw IllegalStateException("stream is not open");
  }
  
  char c;
  int nread = read(sockfd, &c, 1);
  if (nread == 1) {
    ++numRead;
    return c;
  }
  else if (nread == 0) {
    //***cout << "[end of stream - contentLength: " << contentLength << ", numRead: " << numRead << "]" << endl;
    if (contentLength >= 0 && numRead != contentLength) {
      throw NetworkException("number of bytes read differs from content length");
    }
    return -1;
  }
  else {
    throw NetworkException("error occurred reading HTTP response");
  }
}
コード例 #2
0
void ClientSocket::selectEvent()
{
	WSANETWORKEVENTS netEvent;

	::ZeroMemory( &netEvent, sizeof( netEvent ) );
	::WSAEventSelect( m_SocketValue, m_RecvEvent, FD_READ | FD_CLOSE );
	::WSAEnumNetworkEvents( m_SocketValue, m_RecvEvent, &netEvent );

	if( ( netEvent.lNetworkEvents & FD_READ ) == FD_READ )
		onReceive();
 	else if( ( netEvent.lNetworkEvents & FD_CLOSE ) == FD_CLOSE )
		throw NetworkException("ClientSocket::SelectEvent() : 패킷이 닫혔다네");
}
コード例 #3
0
ファイル: Server.cpp プロジェクト: izissise/PFA
void    Server::registerToMaster()
{
  MasterServerRequest   msg;
  std::string           packet;
  ENetEvent             event;
  int			hasEvent;
  bool                  pull = true;
  bool                  passed = false;
  unsigned int		timeout = 3000;
  unsigned int		delay = 50;
  unsigned int		cuTime = 0;

  _masterSocket.connect(_set.getCvar("sv_masterIP"),
                        _set.getCvar("sv_masterPort"),
                        2);
  while (!passed)
    {
      if ((hasEvent = _masterSocket.pullEvent(event, delay, pull)) >= 0)
        {
          switch (event.type)
            {
            case ENET_EVENT_TYPE_CONNECT:
              {
                ServerData      *data = new ServerData;

                msg.set_content(MasterServerRequest::CREATESERVER);
                msg.set_port(_set.getCvar("sv_port"));
                data->set_name(_set.getCvar("sv_hostname"));
                data->set_slots(std::stoul(_set.getCvar("sv_slot")));
                msg.set_allocated_info(data);
                msg.SerializeToString(&packet);
                _masterSocket.sendPacket(0, packet);
                enet_host_flush(_masterSocket.getHost());
                passed = true;
		_masterAuthenticate = true;
              }
	      break;
	    case ENET_EVENT_TYPE_NONE:
	      cuTime += delay;
	      if (cuTime >= timeout)
		passed = true;
              break;
            default:
              break;
            }
        }
      else if (hasEvent < 0)
        throw (NetworkException("Authentification to master server failed"));
    }
  _masterSocket.disconnect();
}
コード例 #4
0
ファイル: Network.cpp プロジェクト: JoshuaBrookover/Jatta
        void __jatta_network_initiate()
        {
#           ifdef JATTA_WINDOWS
            if (!__jatta_network_initiated)
            {
                WSADATA wsaData;
                if (WSAStartup(MAKEWORD(1,1), &wsaData) != 0)
                {
                    throw NetworkException(NetworkExceptionCode::FAILED_STARTUP, NetworkExceptionReason::FAILED_WINSOCK_INITIALIZE);
                }
                __jatta_network_initiated = true;
            }
#           endif
        }
コード例 #5
0
ファイル: LoadVariablesThread.cpp プロジェクト: jlopez/gnash
LoadVariablesThread::LoadVariablesThread(const StreamProvider& sp,
        const URL& url)
	:
	_bytesLoaded(0),
	_bytesTotal(0),
	_stream(sp.getStream(url)),
	_completed(false),
	_canceled(false)
{
	if ( ! _stream.get() )
	{
		throw NetworkException();
	}
}
コード例 #6
0
ファイル: OldUDPSocket.cpp プロジェクト: coredumped/X-VR2
		void OldUDPSocket::send(const void *buf, int size){
			int r;
			r = ::sendto(tsock, buf, size, flags, (struct ::sockaddr *)&ipv4addr, sizeof(ipv4addr));
			if(r == -1){
				switch(errno){
					case ECONNRESET:
						throw ConnectionResetByPeer();
					case ENOMEM:
						throw MemoryException();
					default:
						throw NetworkException();
				}
			}
		}
コード例 #7
0
ファイル: SocketTCP.cpp プロジェクト: lince/libmmi
int SocketTCP::sendData(DataPayload* data) {
	TRACE(logger, "sendData()");

	int bytes = send(_socket, data->data, data->lenght, 0);
	if (bytes < 0) {
		if (bytes < 0) {
			string errMsg = strerror(errno);
			throw NetworkException("int sendData::send(DataPayload* data) \n"
					"Error while sending data:" + errMsg + "\n",
					"br::ufscar::lince::mmi::socketconn::SocketTCP",
					"sendData(DataPayload* )");
		}
	}
	return bytes;
}
コード例 #8
0
ファイル: addrinfo.cpp プロジェクト: k3nju/g2
	//-----------------------------------------------------------------------------------------//
	AddrInfo::AddrInfo( int family,
						int socketType,
						enum cs_type csType,
						const char *node,
						const char *service )
		:result_( NULL )
		{
		int ret = 0;
		result_ = GetAddrInfo( family, socketType, csType, node, service, ret );
		if( result_ == NULL )
			{
			string msg = "getaddrinfo() failed. " + string( gai_strerror( ret ) );
			throw NetworkException( msg, ret, NAME_RESOLUTION_FAILURE );
			}
		}
コード例 #9
0
ファイル: HTTPInputStream.cpp プロジェクト: Iiridayn/sample
void HTTPInputStream::OpenConnection() {
  struct hostent *hostData = gethostbyname(host.c_str());
  if (hostData == NULL || hostData->h_addr == NULL) {
    throw NetworkException(string("could not resolve host name ") + host);
  }
  
  struct sockaddr_in hostAddr;
  bzero(&hostAddr, sizeof(hostAddr));
  hostAddr.sin_family = AF_INET;
  hostAddr.sin_port = htons(port);
  memcpy(&hostAddr.sin_addr, hostData->h_addr, hostData->h_length);

  int s = socket(AF_INET, SOCK_STREAM, 0);
  if (s < 0) {
    throw NetworkException("could not create socket");
  }

  if (connect(s, (struct sockaddr *)&hostAddr, sizeof(hostAddr)) < 0) {
    close(s);
    throw NetworkException(string("could not connect to host ") + host);
  }

  sockfd = s;
}
コード例 #10
0
ファイル: network-config.cpp プロジェクト: vyvy/vasum
void NetworkConfig::addInetConfig(const std::string& ifname, const InetAddr& addr)
{
    auto it = std::find_if(mInterfaces.begin(), mInterfaces.end(),
        [&ifname](const NetworkInterfaceConfig& entry) {
            return entry.getZoneIf() == ifname;
        }
    );

    if (it == mInterfaces.end()) {
        const std::string msg = "No such interface";
        LOGE(msg);
        throw NetworkException(msg);
    }
    it->addInetAddr(addr);
}
コード例 #11
0
ファイル: Socket.cpp プロジェクト: coredumped/X-VR2
		void Socket::close(){
			if(::shutdown(_socket, 2) == -1){
				switch(errno){
					case EBADF:
						throw InvalidFileDescriptor(_socket);
						break;
					case ENOTSOCK:
						throw InvalidSocket(_socket);
						break;
					case ENOTCONN:
						//Lets say you can close it again.
						break;
					default:
						throw NetworkException(errno);
				}
			}
		}
コード例 #12
0
ファイル: psp_network.cpp プロジェクト: Bananattack/verge3
Socket*
ServerSocket::accept()
{
    //if (m_socket == INVALID_SOCKET) {
    //    return NULL;
    //}

    //sockaddr_in addr;
    //int addrlen = sizeof(addr);
    //SOCKET s = ::accept(m_socket, (sockaddr*)&addr, &addrlen);
    //if (s == INVALID_SOCKET) {
    //    return NULL;
    //}

    //return new Socket(s);
	throw NetworkException("accept() unimplemented!");
}
コード例 #13
0
ファイル: SocketTCP.cpp プロジェクト: lince/libmmi
DataPayload* SocketTCP::reciveData() {
	TRACE(logger, "reciveData()");

	unsigned char* buffer = new unsigned char[MAX_BUFFERSIZE];
	int bytes = recv(_socket, buffer, MAX_BUFFERSIZE-1, 0);
	if (bytes <= 0) {
		string errMsg = strerror(errno);
		throw NetworkException("reciveData* SocketTCP::recive()\n"
				"Error while receiving data:" + errMsg  + "\n",
				"br::ufscar::lince::mmi::socketconn::SocketTCP",
				"reciveData()");
	}
	DataPayload* datap = new DataPayload();
	datap->data = new unsigned char [bytes];
	memcpy(datap->data, buffer, bytes);
	datap->lenght = bytes;
	return datap;
}
コード例 #14
0
ファイル: IPAddress.cpp プロジェクト: Zethes/CGUL
/** @details A network address defines the "bottom-most" address for a given network.
 *  @param ip An IP address on the network.
 *  @param netmask The netmask defining the network range.
 *  @returns The network address.
 */
_CGUL_EXPORT CGUL::Network::IPAddress CGUL::Network::IPAddress::CalculateNetwork(const IPAddress& ip, const IPAddress& netmask)
{
    if (!ip.IsValid() || ip.GetType() != netmask.GetType())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_MISMATCH);
    }

    if (ip.GetType() == IPAddressType::IPV4)
    {
        return IPAddress(ip.ToUInt32() & netmask.ToUInt32());
    }
    else
    {
        UInt64 network[2];
        network[0] = ip.address[0] & netmask.address[0];
        network[1] = ip.address[1] & netmask.address[1];
        return IPAddress(network);
    }
}
コード例 #15
0
ファイル: SocketTCP.cpp プロジェクト: lince/libmmi
void SocketTCP::connectSocket() {
	TRACE(logger, "connectSocket()");

	if (isConnected) {
		throw InitializationException("void SocketTCP::connectSocket()\n"
				"Socket is already connected.",
				"br::ufscar::lince::mmi::socketconn::SocketTCP",
				"connectSocket()");
	}
	int ret = connect(_socket, (struct sockaddr *) &addres, sizeof(addres));
	if (ret < 0) {
		string errMsg = strerror(errno);
		throw NetworkException("void SocketTCP::connectSocket()\n"
				"Couldn't connect:" + errMsg  + "\n",
				"br::ufscar::lince::mmi::socketconn::SocketTCP",
				"connectSocket()");
	}
	isConnected = true;
}
コード例 #16
0
ファイル: TCPSocket.cpp プロジェクト: coredumped/X-VR2
		void TCPSocket::create(int protoid){
			_socket = socket(AF_INET, SOCK_STREAM, protoid);
			if(_socket == -1){
				//Socket creation failed
				switch(errno){
					case EPROTONOSUPPORT:
						throw UnsupportedProtocol(errno, protoid);
						break;
					case EACCES:
						break;
					case ENOBUFS:
						break;
					case EMFILE:
					case ENFILE:
					default:
						throw NetworkException(errno);
				}
			}
		}
コード例 #17
0
ファイル: network-config.cpp プロジェクト: vyvy/vasum
void NetworkConfig::addInterfaceConfig(const std::string& hostif,
                                       const std::string& zoneif,
                                       InterfaceType type,
                                       const std::vector<InetAddr>& addrs,
                                       MacVLanMode mode)
{
    auto it = std::find_if(mInterfaces.begin(), mInterfaces.end(),
        [&zoneif](const NetworkInterfaceConfig& entry) {
            return entry.getZoneIf() == zoneif;
        }
    );

    if (it != mInterfaces.end()) {
        const std::string msg = "Interface already exists";
        LOGE(msg);
        throw NetworkException(msg);
    }
    mInterfaces.push_back(NetworkInterfaceConfig(hostif, zoneif, type, addrs, mode));
}
コード例 #18
0
void
SocketBase::doListen() throw(NetworkException)
{
    if ( state == BOUND )
    {
        int res = listen(sockfd, 20);
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            doClose();
            std::stringstream msg;
            msg << "Couldn't listen on socket: " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        state = LISTENING;
    }
    else
    {
        LOGGER.warning("Trying to listen on an unbound socket [%s]", getStateString());
    }
}
コード例 #19
0
void
SocketBase::create () throw(NetworkException)
{
    if ( state == RESOLVED )
    {
        sockfd = socket(PF_INET, addr.socktype, addr.protocol);

        LOGGER.debug("SocketBase:: Create [%s:%d] socket", (addr.socktype == SOCK_STREAM)?"tcp":"udp",sockfd);

        if(sockfd == INVALID_SOCKET)
        {
            lastError = GET_NET_ERROR();
            std::stringstream msg;
            msg << "Couldn't create socket: " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        state = CREATED;
    }
    else
    {
        LOGGER.warning("Trying to recreate a socket [%s]", getStateString());
    }
}
コード例 #20
0
void
SocketBase::bindSocketTo(const Address& toaddr) throw(NetworkException)
{
    if ( state == CONFIGURED )
    {
        int res = bind(sockfd, toaddr.getSockaddr(), toaddr.getSockaddrLen());
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            doClose();
            std::stringstream msg;
            msg << "Couldn't bind socket to address '"
                << toaddr.getIP() << "' port " << toaddr.getPort()
                << ": " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        SocketManager::addSocket(this);
        state = BOUND;
    }
    else
    {
        LOGGER.warning("Trying to bind to a socket != CONFIGURED [%s]", getStateString());
    }
}
コード例 #21
0
void ConnectionManager::Send(int descriptor, const std::string &message) {
  uint16_t length = message.length();
  char* msg = new char[length+sizeof(length)];
  memcpy(msg+sizeof(length), message.c_str(), length);
  length = htons(length);
  memcpy(msg, &length, sizeof(length));
  length = ntohs(length);

  if (!FD_ISSET(descriptor, &clients_)) {
    delete msg;
    throw NetworkException("Client is not registered");
  }

  uint16_t left_to_send = length + sizeof(length);
  uint16_t already_sent = 0;
  while (left_to_send > 0) {
    int sent = send(descriptor, msg+already_sent, left_to_send, 0);
    already_sent += sent;
    left_to_send -= sent;
  }

  delete msg;
}
コード例 #22
0
ファイル: NetworkPlanning.cpp プロジェクト: ddolgushin/study
bool NetworkPlan::buildModel(vector<NodeInfo> nodes) {
	// Установка указателей на начальную и конечную вершины.
	_S = nodes.at(0).n;
	_F = nodes.at(nodes.size() - 1).n;

	// Построение сети по считанной информации.
	_total = nodes.size();

	for (int i = 0; i < _total; i++) {
		NodeInfo* inf = &nodes.at(i);
		NetworkNode* cur = inf->n;
		int size = inf->outLinks.size();

		// Проходим по исходящим номерам, ищем совпадающие
		// узлы и создаём для них ссылки-работы. Попутно проверяем
		// наличие ссылок узлов на самих себя.
		for (int j = 0; j < size; j++) {
			for (int k = 0; k < _total; k++) {
				NodeInfo* tmpInf = &nodes.at(k);

				if (inf->outLinks.at(j).num == tmpInf->n->getNumber()) {
					if (tmpInf->n->getNumber() == inf->n->getNumber())
						throw NetworkException("Ошибка исходных данных:"
							" недопустимы ссылки вершин на самих себя");
					else
						cur->addOutgoingNode(tmpInf->n, inf->outLinks.at(j).len);
				}
			}
		}
	}

	extractLayers();
	numberNodes();

	return true;
}
コード例 #23
0
ファイル: SocketTCP.cpp プロジェクト: JoshuaBrookover/Jatta
/** @brief Starts listening for clients on a specified port.
 *  @param port The port number.
 *  @param ipv4 Whether to use the local ipv4 address or not.  Will use an ipv6 address otherwise.
 *  @param backlog How many clients can wait to be accepted.  Defaults to 10.
 */
void Jatta::Network::SocketTCP::Listen(unsigned short port, bool ipv4, int backlog)
{
    // Convert the port into a string.
    char portString[6];
#   ifdef MSVC
    sprintf_s(portString, "%d", port);
#   else
    sprintf(portString, "%d", port);
#   endif

    // Create a hints variable used to determine the connection configuration.
    struct addrinfo hints;
    memset(&hints, 0, sizeof(addrinfo));

    // Check if IPv4 or IPv6.
    if (ipv4)
    {
        // Use IPv4.
        hints.ai_family = AF_INET;
    }
    else
    {
        // Use IPv6.
        hints.ai_family = AF_INET6;
    }

    // We're setting up a TCP/IP connection, which is a STREAM socket.
    hints.ai_socktype = SOCK_STREAM;

    // Pick the address for us (we'll use a local address)
    hints.ai_flags = AI_PASSIVE;

    // Get the address info using the hints.
    addrinfo* result;
    if (getaddrinfo(NULL, portString, &hints, &result) != 0)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::NO_NETWORK_INTERFACE);
    }

    // Create the socket.
    sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (sock == INVALID_SOCKET)
    {
        freeaddrinfo(result);
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::FAILED_CREATE_SOCKET);
    }

    // Bind the socket to the port.
    if (bind(sock, result->ai_addr, result->ai_addrlen) == SOCKET_ERROR)
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::FAILED_BIND_PORT);
    }

    // Start listening like the champ that we are.
    if (::listen(sock, backlog) == SOCKET_ERROR)
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::FAILED_LISTEN_CALL);
    }

    // Make a non-blocking socket.
    if (!MakeNonBlocking())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::FAILED_NONBLOCKING);
    }

    // Turn off the Nagle Algorithm to increase speed.
    if (!MakeNoDelay())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_LISTEN, NetworkExceptionReason::FAILED_NO_DELAY);
    }

    // Free up the address info linked list.
    freeaddrinfo(result);
}
コード例 #24
0
ファイル: outputmessage.cpp プロジェクト: brun123/otclient
void OutputMessage::checkWrite(int bytes)
{
    if(!canWrite(bytes))
        throw NetworkException("OutputMessage max buffer size reached");
}
コード例 #25
0
ファイル: SocketTCP.cpp プロジェクト: JoshuaBrookover/Jatta
int Jatta::Network::SocketTCP::Peek(void* data, unsigned int size)
{
#   ifdef OpenSSL_FOUND
    if (connectionSecure)
    {
        int amount;
        if (sock == INVALID_SOCKET)
        {
            return false;
        }

        while (true)
        {
            amount = SSL_peek(sslHandle, (char*)data, size);

            if (amount == 0)
            {
                Close();
                return 0;
            }
            else if (amount > 0)
            {
                return amount;
            }

            int error = SSL_get_error(sslHandle, amount);

            if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)
            {
                //Handle these errors then try again.
                //Just waiting it out seems to work.
            }
            else
            {
                throw NetworkException(NetworkExceptionCode::FAILED_PEEK, NetworkExceptionReason::UNKNOWN);
            }
        }
    }
#   endif
    // Check if the socket is valid before we continue.
    if (sock == INVALID_SOCKET)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_PEEK, NetworkExceptionReason::SOCKET_INVALID);
    }

    // Pizza delivery!
    int amount;
    //Peek normally
    if ((amount = ::recv(sock, (char*)data, size, MSG_PEEK)) == SOCKET_ERROR)
    {
        // Check if recv failed because of a WOULDBLOCK error.  This basically means that there was
        // nothing to be received.  In that case, just return 0.  Otherwise, there was an error.
#       ifdef JATTA_WINDOWS
        if (WSAGetLastError() == WSAEWOULDBLOCK)
#       else
        if (errno == EWOULDBLOCK)
#       endif
        {
            return 0;
        }
        else
        {
            throw NetworkException(NetworkExceptionCode::FAILED_PEEK, NetworkExceptionReason::UNKNOWN);
        }
    }

    // Check if recv returned 0, if so, the remove socket disconnected gracefully.
    if (amount == 0)
    {
        Close();
        return 0;
    }
    else
    {
        return amount;
    }
}
コード例 #26
0
ファイル: DNS.cpp プロジェクト: Zethes/CGUL
void CGUL::Network::DNS::Lookup(const CGUL::String& host, Filter filter, List< IPAddress >* addresses)
{
    __cgul_network_initiate();

    // For error checking
    int status;

    addrinfo hints;
    memset(&hints, 0, sizeof(addrinfo));
    hints.ai_family = AF_UNSPEC;
    if (filter == IPV4)
    {
        hints.ai_family = AF_INET;
    }
    if (filter == IPV6)
    {
        hints.ai_family = AF_INET6;
    }
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    addrinfo* result;
    if ((status = getaddrinfo(host.GetCString(), NULL, &hints, &result)) != 0)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_DNS_LOOKUP, status);
    }

    unsigned int count = 0;
    for (addrinfo* p = result; p != NULL; p = p->ai_next)
    {
        count++;
    }

    char ipstr[INET6_ADDRSTRLEN + 1];
    memset(ipstr, 0, INET6_ADDRSTRLEN + 1);
    ipstr[INET6_ADDRSTRLEN - 1] = 0;
    count = 0;
    for (addrinfo* p = result; p != NULL; p = p->ai_next)
    {
        void* addr;

        // Determine if the address is an IPv4 or IPv6 address
        if (p->ai_family == AF_INET)
        {
            struct sockaddr_in *ipv4 = reinterpret_cast< sockaddr_in* >(p->ai_addr);
            addr = &(ipv4->sin_addr);
            struct sockaddr_in in;
            memset(&in, 0, sizeof(in));
            in.sin_family = AF_INET;
            memcpy(&in.sin_addr, addr, sizeof(struct in_addr));
            getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), ipstr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
        }
        else if (p->ai_family == AF_INET6)
        {
            struct sockaddr_in6 *ipv6 = reinterpret_cast< sockaddr_in6* >(p->ai_addr);
            addr = &(ipv6->sin6_addr);
            struct sockaddr_in6 in;
            memset(&in, 0, sizeof(in));
            in.sin6_family = AF_INET6;
            memcpy(&in.sin6_addr, addr, sizeof(struct in6_addr));
            getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), ipstr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
        }

        addresses->Push(IPAddress(ipstr));
    }

    // Free the linked list
    freeaddrinfo(result);
}
コード例 #27
0
ファイル: HTTPRequest.cpp プロジェクト: Zethes/CGUL
bool CGUL::Network::HTTPRequest::PerformRequest(UInt32 timeout)
{
    response = "";
    responseHead = "";
    responseBody = "";

    if (!sock->IsConnected())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_HTTP_REQUEST, NetworkExceptionReason::SOCKET_INVALID);
    }

    sock->Send((const void*)request.GetCString(), request.GetSize());

    char buffer[1024];

    // Wait for the response.
    Timer timeoutTimer;
    timeoutTimer.Start();
    while (sock->Peek(buffer, 1) == 0 && (timeoutTimer.GetElapsedMilliseconds() < timeout || timeout == 0))
    {
        if (!sock->IsConnected())
        {
            throw NetworkException(NetworkExceptionCode::FAILED_HTTP_REQUEST, NetworkExceptionReason::SOCKET_INVALID);
        }
    }
    timeoutTimer.Stop();

    if (timeoutTimer.GetElapsedMilliseconds() >= timeout && timeout != 0)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_HTTP_REQUEST, NetworkExceptionReason::TIMEOUT);
    }

    //Get the headers length.
    int headSize = 0;
    sock->Peek(buffer, 1024);
    CGUL::String bufferString = buffer;
    headSize = bufferString.FindFirstOf("\r\n\r\n")+4;

    //Get the reponse's head.
    char* bufferHead = new char[headSize];
    sock->Receive(bufferHead, headSize);
    responseHead += bufferHead;

    //Parse the Response Header
    ParseResponseHead();

    //Get the reponse's body.
    int amount = 0;

    switch (header.transferEncoding)
    {
        case HTTPTransferEncoding::CONTENT_LENGTH:
        {
            unsigned int count = 0;
            while (sock->IsConnected())
            {
                unsigned int size = 1024;
                if (count + size > header.contentLength)
                {
                    size = header.contentLength - count;
                }

                char* buff = new char[size];
                amount = sock->Receive((void*)buff, size);
                count += amount;
                if (amount > 0)
                {
                    responseBody += EncodeString(buff, size);
                }

                if (count >= header.contentLength)
                {
                    break;
                }
            }
            break;
        }

        case HTTPTransferEncoding::CHUNKED:
        {
            char * sizeBuffer = new char[64];

            while (sock->IsConnected())
            {
                //Get the size.
                amount = sock->Peek(sizeBuffer, 64);
                if (amount <= 0)
                {
                    break;
                }

                String sizeString = "";
                for (int i = 0; i < amount; i++)
                {
                    if (sizeBuffer[i] == '\r')
                    {
                        if (sizeBuffer[i+1] == '\n')
                        {
                            break;
                        }
                        throw NetworkException(NetworkExceptionCode::FAILED_HTTP_REQUEST, NetworkExceptionReason::UNKNOWN);
                    }
                    else
                    {
                        sizeString += sizeBuffer[i];
                    }
                }
                //Convert from hex to decimal
                unsigned int size = 0;
                for (unsigned j = 0; j < sizeString.GetLength(); j++)
                {
                    char code = sizeString[sizeString.GetLength()-j-1];
                    if (code >= 48 && code <= 57) //Number
                    {
                        size += (code - 48)*((j == 0) ? 1 : 16*j);
                    }
                    if (code >= 65 && code <= 70) //A-F
                    {
                        size += (code - 55)*((j == 0) ? 1 : 16*j);
                    }
                    if (code >= 97 && code <= 102) //a-f
                    {
                        size += (code - 87)*((j == 0) ? 1 : 16*j);
                    }
                }
                sock->Receive(sizeBuffer, sizeString.GetLength()+2);

                if (size == 0) //If the size is 0, then we are done
                {
                    break;
                }
                size += 2;

                //Otherwise receive the next chunk and add a new line (\r\n)
                char* buff = new char[size];
                amount = sock->Receive((void*)buff, size);
                responseBody += EncodeString(buff, size);
            }
            break;
        }

        default:
        {
            throw NetworkException(NetworkExceptionCode::FAILED_HTTP_REQUEST, NetworkExceptionReason::UNKNOWN_TRANSFER_ENCODING);
            break;
        }
    }

    response = responseHead + responseBody;

    if (header.connection == Network::HTTPConnections::CLOSE)
    {
        Close();
    }

    return true;
}
コード例 #28
0
TcpSocket* TcpSocket::doBind() {
	if(bind(getSocket(),(sockaddr *)getAddr(),sizeof(sockaddr_in)) ==
		 SOCKET_ERROR)
		throw NetworkException("bind", errno);
	return this;
}
コード例 #29
0
ファイル: SocketTCP.cpp プロジェクト: JoshuaBrookover/Jatta
/** @brief Connects to a server on a given ip and port.
 *  @param ip The IP address to connect to.
 *  @param port The port number.
 */
void Jatta::Network::SocketTCP::Connect(const IPAddress& ip, unsigned short port)
{
    // Check that the IP is valid
    if (!ip.IsValid())
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::ADDRESS_INVALID);
    }

    // Create a hints variable used to determine the connection configuration.
    struct addrinfo hints;
    memset(&hints, 0, sizeof(addrinfo));

    // Check if the IP is an IPv4 or IPv6.
    if (ip.GetType() == IPAddressType::IPV4)
    {
        // Use IPv4.
        hints.ai_family = AF_INET;
    }
    else
    {
        // Use IPv6.
        hints.ai_family = AF_INET6;
    }

    // We're setting up a TCP/IP connection, which is a STREAM socket.
    hints.ai_socktype = SOCK_STREAM;

    // Convert the port into a string.
    char portString[6];
#   ifdef MSVC
    sprintf_s(portString, "%d", port);
#   else
    sprintf(portString, "%d", port);
#   endif

    // Get the address info using the hints.
    addrinfo* result;
    if (getaddrinfo(ip.ToString().GetCString(), portString, &hints, &result) != 0)
    {
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::NO_NETWORK_INTERFACE);
    }

    // Create the socket.  Because our hints are so strict, we don't have to worry about looping
    // through the linked list.  We should be able to trust that the first result is what we want.
    sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (sock == INVALID_SOCKET)
    {
        freeaddrinfo(result);
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_CREATE_SOCKET);
    }

    // Make the connection.
    if (::connect(sock, result->ai_addr, result->ai_addrlen) == SOCKET_ERROR)
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_CONNECT_CALL);
    }

    // Make a non-blocking socket.
    if (!MakeNonBlocking())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_NONBLOCKING);
    }

    // Turn off the Nagle Algorithm to increase speed.
    if (!MakeNoDelay())
    {
        freeaddrinfo(result);
        Close();
        throw NetworkException(NetworkExceptionCode::FAILED_CONNECT, NetworkExceptionReason::FAILED_NO_DELAY);
    }

    // Free up the address info linked list.
    freeaddrinfo(result);
}