Example #1
0
/**
 * Removes a connection from the bandwidth allocator
 * Requests all other connections update their speed
 */
int BandwidthAllocator::removeBandwidth(TCPConnection* connection) {
	boost::unique_lock<boost::mutex> lock(queueMutex);

	// If we are not in a consistant state - wait
	while(unsettled.size() > 0 || currentlyWorking) queueWaiting.wait(lock);

	printf("1\n");
	currentlyWorking = true;

	int removeConnectionFd = connection->getSockFd();
	int numConnections = settled.size();
	int nodeSpeed = UPLINK_SPEED;
	if (numConnections != 1) nodeSpeed = UPLINK_SPEED / (numConnections - 1);
	printf("2\n");
	TCPConnection* currentConnection;
	for (int i = 0; i < numConnections; i++) {
		currentConnection = settled.front();
		settled.pop();
		if (currentConnection->getSockFd() != removeConnectionFd) {
		currentConnection->updateRemoteSpeed(nodeSpeed);
		unsettled[currentConnection->getSockFd()] = currentConnection;
		}
	}
	printf("3\n");
	while(unsettled.size() > 0) queueWaiting.wait(lock);
	printf("4\n");
	currentlyWorking = false;
	queueWaiting.notify_all();
	printf("5\n");
	return 0;

}
Example #2
0
/**
 * Allocates some bandwidth for the new TCP connection
 * Notifies all the other connections to change their speed
 */
int BandwidthAllocator::getBandwidth(TCPConnection* connection) {
	boost::unique_lock<boost::mutex> lock(queueMutex);

	while(unsettled.size() > 0 || currentlyWorking) queueWaiting.wait(lock);

	int numConnections = settled.size();
	int nodeSpeed = UPLINK_SPEED / (numConnections + 1);

	TCPConnection* currentConnection;
	for (int i = 0; i < numConnections; i++) {
		currentConnection = settled.front();
		settled.pop();
		unsettled[currentConnection->getSockFd()] = currentConnection;
		currentConnection->updateRemoteSpeed(nodeSpeed);
	}

	puts("Waiting for unsettled to sort itself out...");
	while(unsettled.size() > 0) queueWaiting.wait(lock);

	settled.push(connection);

	currentlyWorking = false;
	queueWaiting.notify_all();

	// Return the speed we need to run at
	// When we update this to handle flows at any time reverse so
	// we send a bandwidth alloc to the receipent
	return nodeSpeed;

}
Example #3
0
bool HTTPServer_Impl::read_lines(TCPConnection &connection, std::string &out_header_lines)
{
	out_header_lines.clear();
	while (out_header_lines.length() < 32*1024)
	{
		char buffer[1024];
		if (connection.get_read_event().wait(15000) == false)
			throw Exception("Read timed out");
		int bytes_read = connection.peek(buffer, 1024);
		if (bytes_read <= 0)
			break;
		std::string str(buffer, bytes_read);
		std::string::size_type start_pos = out_header_lines.length();
		out_header_lines += str;
		std::string::size_type pos = out_header_lines.find("\r\n\r\n");
		if (pos == std::string::npos)
		{
			connection.receive(buffer, bytes_read);
		}
		else
		{
			connection.receive(buffer, pos+4-start_pos);
			out_header_lines.resize(pos+4);
			return true;
		}
	}
	return false;
}
Example #4
0
int main()
{
	TCPConnection* pconnect = new TCPConnection();
	pconnect->active_open();
	pconnect->active_open();
	pconnect->active_open();
	pconnect->active_open();
	pconnect->active_open();
}
Example #5
0
Image Receive::apply(int port) {
    // create and bind the server if it hasn't already been created
    if (!servers[port]) {
        servers[port] = new TCPServer(port);
    }

    printf("Listening on port %i\n", port);
    TCPConnection *conn = servers[port]->listen();
    printf("Got a connection, reading image...\n");

    Image im = conn->recvImage();

    delete conn;   
    return im;
}
Example #6
0
int main()
{

	//unsigned short port = 8080;
	TCPConnection *MyConnection = new TCPConnection();
	MyConnection->Listen();
	MyConnection->Start();

	while(1)
	{
		this_thread::sleep_for(std::chrono::milliseconds(1));

		//sleep(5);
	}
	return 0;
}
Example #7
0
void send_request(TCPConnection &connection)
{
	std::string request =
		"HEAD /index.html HTTP/1.1\r\n"
		"Host: www.clanlib.org\r\n"
		"\r\n";

	NetworkConditionVariable wait_condition;
	std::mutex mutex;
	std::unique_lock<std::mutex> lock(mutex);

	size_t pos = 0;
	while (pos < request.length())
	{
		int bytes_written;
		while (true)
		{
			bytes_written = connection.write(request.data() + pos, request.length() - pos);
			if (bytes_written != -1)
				break;

			NetworkEvent *events[] = { &connection };
			wait_condition.wait(lock, 1, events);
		}
		pos += bytes_written;
	}
}
Example #8
0
void TCPConnection::ThreadListen(void* arg)
{
	//printf("ThreadListe\n");
	TCPConnection *MyClass = static_cast<TCPConnection*>(arg);

	while(MyClass->mRunningListenFlag)
	{
		fd_set rfd; // read event
		fd_set efd; // accept event
		int retVal, nfds = 0;
		timeval tv = { 0 };
		tv.tv_usec = 1;


		FD_ZERO(&rfd);
		FD_ZERO(&efd);

		FD_SET(MyClass->mSocketListener, &rfd);
		nfds = nfds > MyClass->mSocketListener ? nfds : MyClass->mSocketListener;
		FD_SET(MyClass->mSocketListener, &efd);
		nfds = nfds > MyClass->mSocketListener ? nfds : MyClass->mSocketListener;

		retVal = select(nfds + 1, &rfd, NULL, & efd, &tv);

		if (retVal == -1 && errno == EINTR)
			return ;

		if (FD_ISSET(MyClass->mSocketListener, &efd))
		{
			char c;
			retVal = recv(MyClass->mSocketListener, &c, 1, MSG_OOB);
		}

		if (FD_ISSET(MyClass->mSocketListener, &rfd))
		{
			//if(MyClass->mSocketPc == -1)
				MyClass->OnAccept(MyClass->mSocketListener);
			//else
				//printf("Reject connection from PC !!!!\n");

		}

	}
}
Example #9
0
	void NetGameServer::listen_thread_main()
	{
		while (true)
		{
			std::unique_lock<std::mutex> lock(impl->mutex);
			if (impl->stop_flag)
				break;

			NetworkEvent *events[] = { impl->tcp_listen.get() };
			impl->worker_event.wait(lock, 1, events);

			SocketName peer_endpoint;
			TCPConnection connection = impl->tcp_listen->accept(peer_endpoint);
			if (!connection.is_null())
			{
				std::unique_ptr<NetGameConnection> game_connection(new NetGameConnection(this, connection));
				impl->connections.push_back(game_connection.release());
			}
		}
	}
Example #10
0
DataBuffer receive_response(TCPConnection &connection)
{
	std::array<char, 16000> response_data;

	NetworkConditionVariable wait_condition;
	std::mutex mutex;
	std::unique_lock<std::mutex> lock(mutex);

	size_t pos = 0;
	while (pos < response_data.size())
	{
		size_t last_pos = pos > 0 ? pos - 4 : pos;

		int bytes_read;
		while (true)
		{
			bytes_read = connection.read(response_data.data() + pos, response_data.size() - pos);
			if (bytes_read != -1)
				break;

			NetworkEvent *events[] = { &connection };
			wait_condition.wait(lock, 1, events);
		}
		pos += bytes_read;

		if (bytes_read == 0)
			break;

		bool end_header_found = false;
		for (size_t i = last_pos; i + 3 < pos; i++)
		{
			if (response_data[i] == '\r' && response_data[i + 1] == '\n' && response_data[i + 2] == '\r' && response_data[i + 3] == '\n')
			{
				end_header_found = true;
				break;
			}
		}

		if (end_header_found)
			break;
	}

	for (auto &line : StringHelp::split_text(std::string(response_data.data(), pos), "\r\n"))
	{
		Console::write_line(StringHelp::local8_to_text(line));
	}

	return DataBuffer();
}
Example #11
0
		void run()
		{
			const char* testData = "Twenty-five or six to four";
			const size_t testDataLen = strlen(testData);
			char* buff = reinterpret_cast<char*>(calloc(testDataLen + 1, 1));

			const int port = 1337;

			try {
				// Create a listener and a client connection
				TCPListener server(port);
				TCPConnection client;

				// Start the server and connect to it
				server.start();
				client.connect(IPEndPoint(IP(127, 0, 0, 1), port));

				// Accept the connection
				auto serverConn = server.accept();

				// Test sending from the server to the client
				serverConn->send(testData, testDataLen);
				client.receive(buff, testDataLen);

				if (strcmp(testData, buff) != 0)
					throw TestFailedException("Data sent from server to client didn't go through properly");

				// Reset the buffer and try sending from
				// the client to the server
				memset(buff, 0, testDataLen);

				serverConn->shutDownSending();
				client.shutDownReceiving();

				client.send(testData, testDataLen);
				serverConn->receive(buff, testDataLen);

				if (strcmp(testData, buff) != 0)
					throw TestFailedException("Data sent from client to server didn't go through properly");

				// Shut down the connections
				client.disconnect();

				if (serverConn->receive(buff, testDataLen) != 0)
					throw TestFailedException("The server was not notified when the client disconnected");

				serverConn->disconnect();

				free(buff);
			}
			catch (...) {
				free(buff);
				throw;
			}
		}
Example #12
0
ThreadReturnType TCPConnection::TCPConnectionLoop(void* tmp)
{
#ifdef _WINDOWS
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif
	if (tmp == 0)
	{
		THREAD_RETURN(nullptr);
	}
	TCPConnection* tcpc = (TCPConnection*) tmp;
#ifndef WIN32
	//Log.Out(Logs::Detail, Logs::TCP_Connection, "%s Starting TCPConnectionLoop with thread ID %d", __FUNCTION__, pthread_self());
#endif
	tcpc->MLoopRunning.lock();
	while (tcpc->RunLoop())
	{
		Sleep(LOOP_GRANULARITY);
		if (!tcpc->ConnectReady())
		{
			if (!tcpc->Process())
			{
				//the processing loop has detecting an error..
				//we want to drop the link immediately, so we clear buffers too.
				tcpc->ClearBuffers();
				tcpc->Disconnect();
			}
			Sleep(1);
		}
		else if (tcpc->GetAsyncConnect())
		{
			tcpc->SetAsyncConnect(false);
		}
		else
		{
			Sleep(10);	//nothing to do.
		}
	}
	tcpc->MLoopRunning.unlock();

#ifndef WIN32
	//Log.Out(Logs::Detail, Logs::TCP_Connection, "%s Ending TCPConnectionLoop with thread ID %d", __FUNCTION__, pthread_self());
#endif
	THREAD_RETURN(nullptr);
}
Example #13
0
      void run(Thread *thread, void *args)
      {
	TCPConnection *conn = static_cast<TCPConnection *>(args);
	conn->writeData();
      }
Example #14
0
void HTTPServer_Impl::write_line(TCPConnection &connection, const std::string &line)
{
	connection.send(line.data(), line.length(), true);
	connection.send("\r\n", 2, true);
}
Example #15
0
void HTTPServer_Impl::connection_thread_main(TCPConnection connection)
{
	try
	{
		std::string request;
		bool bool_result = read_line(connection, request);
		if (bool_result == false)
		{
			connection.disconnect_abortive();
			return;
		}

		std::string headers;
		bool_result = read_lines(connection, headers);
		if (bool_result == false)
		{
			connection.disconnect_abortive();
			return;
		}

		// Extract request command, url and version:

		std::string command, url, version;
		std::string::size_type pos1 = request.find(' ');
		if (pos1 == std::string::npos)
			throw Exception("Bad request");
		command = request.substr(0, pos1);
		if (command != "POST" && command != "GET")
			throw Exception("Unsupported");
		std::string::size_type pos2 = request.find(' ', pos1 + 1);
		if (pos2 == std::string::npos)
			throw Exception("Bad request");
		url = request.substr(pos1+1, pos2-pos1-1);
		std::string::size_type pos3 = request.find(' ', pos2 + 1);
		if (pos3 != std::string::npos)
			throw Exception("Bad request");
		version = request.substr(pos2 + 1);

		DataBuffer request_data;

		// Handle request:

		// Look for a request handler that will deal with the HTTP request:
		MutexSection mutex_lock(&mutex);
		std::vector<HTTPRequestHandler>::size_type index, size;
		size = handlers.size();
		bool handled = false;
		for (index = 0; index < size; index++)
		{
			if (handlers[index].is_handling_request(command, url, headers))
			{
				HTTPRequestHandler handler = handlers[index];
				mutex_lock.unlock();

				if (command == "POST")
				{
					write_line(connection, "HTTP/1.1 100 Continue");
					// write_line(connection, "Content-Length: 0");
					write_line(connection, "");
				}

				std::shared_ptr<HTTPServerConnection_Impl> connection_impl(std::make_shared<HTTPServerConnection_Impl>());
				connection_impl->connection = connection;
				connection_impl->request_type = command;
				connection_impl->request_url = url;
				connection_impl->request_headers = headers;
				HTTPServerConnection http_connection(connection_impl);
				handler.handle_request(http_connection);
				handled = true;
				break;
			}
		}
		mutex_lock.unlock();

		if (!handled)
		{
			// No handler wants it.  Reply with 404 Not Found:
			std::string error_msg("404 Not Found");
			write_line(connection, "HTTP/1.1 404 Not Found");
			write_line(connection, "Server: ClanLib HTTP Server");
			write_line(connection, "Connection: close");
			write_line(connection, "Vary: *");
			write_line(connection, "Content-Type: text/plain");
			write_line(connection, "Content-Length: " + StringHelp::int_to_local8(error_msg.length()+2));
			write_line(connection, "");
			write_line(connection, error_msg);
		}

		connection.disconnect_graceful();

/*
		if (url == "/")
		{
			File file("Sources/test.html", File::open_existing);
			DataBuffer response(file.get_size());
			file.read(response.get_data(), response.get_size(), true);
			file.close();

			// Send back response.

			write_line(connection, "HTTP/1.1 200 OK");
			write_line(connection, "Server: ClanLib HTTP Server");
			write_line(connection, "Connection: close");
//			write_line(connection, "Date: Sun, 16 Oct 2005 20:13:00 GMT");
//			write_line(connection, "Expires: Sun, 16 Oct 2005 20:13:00 GMT");
			write_line(connection, "Vary: *");
//			write_line(connection, "ETag: \"foobar\"");
			write_line(connection, "Content-Type: text/html");
			write_line(connection, "Content-Length: " + StringHelp::int_to_local8(response.get_size()));
			write_line(connection, "");
			connection.send(response.get_data(), response.get_size(), true);
		}
		else
		{
			DataBuffer response;
			bool error = false;
			try
			{
				response = handle_request(url, headers, request_data);
			}
			catch (const Exception &e)
			{
//					write_line(connection, "HTTP/1.1 404 Not Found");
				write_line(connection, "HTTP/1.1 404 Not Found");
				write_line(connection, "Server: ClanLib HTTP Server");
				write_line(connection, "Connection: close");
//				write_line(connection, "Date: Sun, 16 Oct 2005 20:13:00 GMT");
//				write_line(connection, "Expires: Sun, 16 Oct 2005 20:13:00 GMT");
				write_line(connection, "Vary: *");
//				write_line(connection, "ETag: \"foobar\"");
				write_line(connection, "Content-Type: text/plain");
				write_line(connection, "Content-Length: 0");
				write_line(connection, "");
				error = true;
			}

			// Send back response.

			if (!error)
			{
				write_line(connection, "HTTP/1.1 200 OK");
				write_line(connection, "Server: ClanLib HTTP Server");
				write_line(connection, "Connection: close");
//				write_line(connection, "Date: Sun, 16 Oct 2005 20:13:00 GMT");
//				write_line(connection, "Expires: Sun, 16 Oct 2005 20:13:00 GMT");
				write_line(connection, "Vary: *");
//				write_line(connection, "ETag: \"foobar\"");
				write_line(connection, "Content-Type: text/xml");
				write_line(connection, "Content-Length: " + StringHelp::int_to_local8(response.get_size()));
				write_line(connection, "");
				connection.send(response.get_data(), response.get_size(), true);
			}
		}
*/
	}
	catch (const Exception& e)
	{
		log_event("error", e.message);
	}
}
Example #16
0
int main(int argc, char* argv[]){

	gst_init(&argc,&argv);
	char serverIP[SIZEOFCHARARRAY];
	DataBaseAccess *dBA = new DataBaseAccess();
	cout<<"\nCreate Main Function DBA\n";
	dBA->ClearRtspTable();

	if ( CheckValidation( dBA, serverIP ) ){
		int channelCount = dBA->IsChannelsExist( dBA->GetSystemDID() );
		Notification * notification = new Notification();
		Retrieve * RetrieveObj = new Retrieve( serverIP, BroadCastStreamPortNumber, LocalStreamPortNumber );
		RetrieveObj->StartThreadForVideoEntry(RetrieveObj);

		VOD* VODObj = new VOD(serverIP, VODPortNumber );

		BootLoader* BootLoaderObj = new BootLoader( RetrieveObj );
		BootLoaderObj->StartBoot();
		Failover * failover = new Failover(BootLoaderObj);

		if  ( channelCount == 0 ){
			failover->StartThread(failover);
		}
		else
			failover->isBreak = true;


		Interaction * interaction = new Interaction(failover);
		interaction->InitializeThread(interaction);

		TCPConnection* TCPConnectionDesktop = new TCPConnection( tcpSocketPortNumber, RetrieveObj, VODObj, notification, false,failover,interaction );
		if( !TCPConnectionDesktop->StartInternalThread() )
			cout<<"Failed to create thread\n";

		TCPConnection* TCPConnectionAndroid = new TCPConnection( AndroidTcpSocketPortNumber, RetrieveObj, VODObj, notification, true,failover,interaction  );
		if( !TCPConnectionAndroid->StartInternalThread() )
			cout<<"Failed to create thread\n";
		else
			cout<<"\nTcp Connection Created\n";
		usleep(5);

		//Monitoring *monitoring = new Monitoring(dBA);

#if STARTPROCESSMONITORING
		cout<<"\nStarting Monitoring\n";
		Monitoring *monitoring;
		monitoring = new Monitoring();
		monitoring->StartInternalThread();
#endif


		dBA->Close();
		delete dBA;
		cout<<"\n Close Main Function DBA\n";
		TCPConnectionDesktop->WaitForInternalThreadToExit();
		TCPConnectionAndroid->WaitForInternalThreadToExit();


		delete VODObj;
		delete TCPConnectionDesktop;
		delete TCPConnectionAndroid;
		delete interaction;
		delete RetrieveObj;
		delete failover;
		delete BootLoaderObj;
		delete notification;
	}
	else{
		dBA->Close();
		delete dBA;
	}
	return 0;
}
Example #17
0
  void TCPCONNECTIONTF::testReadData() {
    ANET_LOG(DEBUG, "BEGIN testReadData()");
    Socket *client = new Socket;
    client->setAddress("localhost", 12345);
    client->connect();
    Socket *accept = _server->accept();
    CPPUNIT_ASSERT(accept);

    //    ConnPacketFactory *factory = new ConnPacketFactory;
    //    DefaultPacketStreamer *streamer = new DefaultPacketStreamer(factory);
    
    //tricket 47
    TCPConnection *tmpConn = new TCPConnection(accept, _streamer, NULL);
    DataBuffer buffer;
    buffer.writeInt32(ANET_PACKET_FLAG + 1);
    buffer.writeInt32(111);
    buffer.writeInt32(222);
    const char *data = "just for test";
    buffer.writeInt32(strlen(data) - 1);
    buffer.writeBytes(data, strlen(data));
    ANET_LOG(DEBUG, "buffer(%p) length:(%d)",&buffer, buffer.getDataLen());
    client->write(buffer.getData(), buffer.getDataLen());
    CPPUNIT_ASSERT(!tmpConn->readData());

    buffer.clear();
    buffer.writeInt32(ANET_PACKET_FLAG);
    buffer.writeInt32(111);
    buffer.writeInt32(222);
    buffer.writeInt32(-1);
    buffer.writeBytes(data, strlen(data));
    client->write(buffer.getData(), buffer.getDataLen());
    CPPUNIT_ASSERT(!tmpConn->readData());

    buffer.clear();
    buffer.writeInt32(ANET_PACKET_FLAG);
    buffer.writeInt32(111);
    buffer.writeInt32(222);
    buffer.writeInt32(strlen(data)/2);
    buffer.writeBytes(data, strlen(data));
    client->write(buffer.getData(), buffer.getDataLen());
    CPPUNIT_ASSERT(!tmpConn->readData());
    delete tmpConn;
    delete accept;
    client->close();
    delete client;

    //    TCPConnection *conn = new TCPConnection(_client, NULL, NULL);
    
    _conn->setServer(false);
    _conn->postPacket(new ConnPacket(11), _handler, NULL);
    _conn->postPacket(new ConnPacket(21), _handler, NULL);
    _conn->postPacket(new ConnPacket(31), _handler, NULL);
    _conn->writeData();

    // flag(0x416e457) chid pcode datalen 
    //DataBuffer *input = &_conn->_input;
    TCPServerAdapter *adapter = new TCPServerAdapter;
    TCPConnection *connAcc = 
      new TCPConnection(_accept, _streamer, adapter);
    connAcc->setServer(true);
    connAcc->_streamer = _streamer;
    connAcc->_iocomponent = 
      new TCPComponent(_transport, _accept);
    //connAcc->_streamer, NULL);
    CPPUNIT_ASSERT(connAcc->readData());
    CPPUNIT_ASSERT_EQUAL(3, adapter->handNum);

    //test error packet
    adapter->reset(); //set the hand packet num to zero
    _conn->postPacket(new ConnPacket(20, 11), _handler, NULL);
    _conn->postPacket(new ConnPacket(20, 30), _handler, NULL);
    CPPUNIT_ASSERT(_conn->writeData());
    CPPUNIT_ASSERT(connAcc->readData());
    CPPUNIT_ASSERT_EQUAL(2, adapter->handNum);

    ANET_LOG(SPAM, "connAcc(%p), ioc (%p)", connAcc, connAcc->_iocomponent);
    delete connAcc->_iocomponent;
    delete connAcc;
    _accept = NULL;
    delete adapter;
    ANET_LOG(DEBUG,"END testReadData()");
  }
Example #18
0
ThreadReturnType TCPConnection::TCPConnectionLoop(void* tmp) {
#ifdef _WINDOWS
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif
	if (tmp == 0) {
		THREAD_RETURN(NULL);
	}
	TCPConnection* tcpc = (TCPConnection*) tmp;
#ifndef WIN32
	_log(COMMON__THREADS, "Starting TCPConnectionLoop with thread ID %d", pthread_self());
#endif
	tcpc->MLoopRunning.lock();
	while (tcpc->RunLoop()) {
		Sleep(LOOP_GRANULARITY);
		if (!tcpc->ConnectReady()) {
			_CP(TCPConnectionLoop);
			if (!tcpc->Process()) {
				//the processing loop has detecting an error.. 
				//we want to drop the link immediately, so we clear buffers too.
				tcpc->ClearBuffers();
				tcpc->Disconnect();
			}
			Sleep(1);
		}
		else if (tcpc->GetAsyncConnect()) {
			_CP(TCPConnectionLoop);
			if (tcpc->charAsyncConnect)
				tcpc->Connect(tcpc->charAsyncConnect, tcpc->GetrPort());
			else
				tcpc->ConnectIP(tcpc->GetrIP(), tcpc->GetrPort());
			tcpc->SetAsyncConnect(false);
		}
		else
			Sleep(10);	//nothing to do.
	}
	tcpc->MLoopRunning.unlock();
	
#ifndef WIN32
	_log(COMMON__THREADS, "Ending TCPConnectionLoop with thread ID %d", pthread_self());
#endif
	
	THREAD_RETURN(NULL);
}