void test_case() {
	Key keys[2];

	keys[0].ip = 0x12345678;
	keys[0].port = 0x9abc;

	keys[1].ip = 0x87654321;
	keys[1].port = 0xfedc;

	setTransmitters(keys, 1);

	char message[17];
	char extraMessage[17];

	generateMessage(message, 1);

	char* msg = message;

	assertLongEquals("Returned msg should has regular type",
					 1, *msg & 0xff);
	assertLongEquals("Returned msg should eq what send",
					 0x78, msg[1] & 0xff);
	assertLongEquals("Returned msg should eq what send",
					 0x9a, msg[6] & 0xff);

	generateMessage(message, 0);
	generateMessage(extraMessage, 1);

	assertLongEquals("Returned msg should has alterHashTable type",
					 2, *msg & 0xff);
	assertLongEquals("Returned msg again should has regular type",
					 1, extraMessage[0] & 0xff);
	assertLongEquals("Returned msg should eq what send",
					 0x78, msg[1] & 0xff);
	assertLongEquals("Returned msg should eq what send",
					 0x9a, msg[6] & 0xff);

	assertLongEquals("Should return generated msg",
					 msg[7] & 0xff, extraMessage[1] & 0xff);
	assertLongEquals("Should return generated msg",
					 msg[8] & 0xff, extraMessage[2] & 0xff);
	assertLongEquals("Should return generated msg",
					 msg[12] & 0xff, extraMessage[6] & 0xff);

}
Example #2
0
void
Txc13::initialize()
{
    if (getIndex() == 0)
    {
        // Boot the process scheduling the initial message as self message.
        TicTocMsg13 *msg = generateMessage();
        scheduleAt(0.0, msg);
    }
}
Example #3
0
File: main.cpp Project: xtuer/Qt
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QHostAddress multicastAddress("225.20.40.20"); // Multicast 组的地址
    QUdpSocket *udpSocket = new QUdpSocket();
    int messageCount = 10;

    for (int i = 0; i < messageCount; ++i) {
        QString data = generateMessage(i, '*');
        // 使用 Unicast 发送消息
        udpSocket->writeDatagram(data.toUtf8(), multicastAddress, 13930);
        qDebug() << data;
    }

    return a.exec();
}
Example #4
0
void
Txc14::initialize()
{
    // Initialize variables.
    sentPkgs = 0;
    receivedPkgs = 0;
    // Make them observable.
    WATCH(sentPkgs);
    WATCH(receivedPkgs);

    if (getIndex() == 0)
    {
        // Boot the process scheduling the initial message as self message.
        TicTocMsg14 *msg = generateMessage();
        scheduleAt(0.0, msg);
    }
}
Example #5
0
void TeamMessageHandler::update(BHumanMessageOutputGenerator& outputGenerator)
{
  outputGenerator.theBHumanArbitraryMessage.queue.clear();

  outputGenerator.sendThisFrame =
#ifndef SITTING_TEST
#ifdef TARGET_ROBOT
    !(theMotionRequest.motion == MotionRequest::specialAction && theMotionRequest.specialActionRequest.specialAction == SpecialActionRequest::playDead) &&
    !(theMotionInfo.motion == MotionRequest::specialAction && theMotionInfo.specialActionRequest.specialAction == SpecialActionRequest::playDead) &&
#endif
#endif // !SITTING_TEST
    theFrameInfo.getTimeSince(timeLastSent) >= sendInterval;

  outputGenerator.generate = [this, &outputGenerator](RoboCup::SPLStandardMessage* const m)
  {
    generateMessage(outputGenerator);
    writeMessage(outputGenerator, m);
  };
}
Example #6
0
void SimpleGen::handleMessage(cMessage* msg)
{
	if (msg == event)
	{
		// Calculate delay
		double delay = getDelay();

		emit(eventSignal, delay);

		if (canSendMessage())
		{
			// It's time to send message, so prepare new one and send
			send(generateMessage(), "out");
		}

		// Send next message after delay
		scheduleAt(simTime() + delay, event);
	}
	else
	{
		// This should never happen, but for sure delete
		delete msg;
	}
}
Example #7
0
void
Txc13::handleMessage(cMessage *msg)
{
    // check_and_cast from omnetpp.h perform a dynamic cast or raise an error
    // during the simulation instead of crash.
    TicTocMsg13 *ttmsg = check_and_cast<TicTocMsg13 *>(msg);
    if (ttmsg->getDestination() == getIndex())
    {
        // Message arrived.
        EV << "Message " << msg <<" arrived.\n";
        bubble("ARRIVED, starting a new one.");
        delete ttmsg;

        // Generate another message.
        TicTocMsg13 *newmsg = generateMessage();
        EV <<newmsg << endl;
        forwardMessage(newmsg);
    }
    else
    {
        // We need to forward the message.
        forwardMessage(ttmsg);
    }
}
Example #8
0
int main(){
	pid_t pid;
	int fluxo, msgKind;
	char userName[50];
	char *bufferRcv, *_bufferRcv, *msgContent;	
	
	struct userList _users;
	struct messageList _messages;
	
	int localSocket,remoteSocket,structSize;
	struct sockaddr_in local;
	struct sockaddr_in remote;
		
	//Inicio da execução
	
	system("clear");
	//Apagando todos os dados de seções passadas
	deleteFile();
	//Criando diretórios necessários
	makeDirectory();
	//Mensagem de inicio
	printf("Servidor iniciado\n");
	
	//Configurações do socket local
	//Mais detalhes consulte as manpages
	localSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(localSocket == -1)
		errorSocket();
		
	//Configuração do socket local
	//Mais detalhes consulte as manpages
	local.sin_family = AF_INET; 
	local.sin_port = htons(31337);  	
	local.sin_addr.s_addr = INADDR_ANY;
	memset(local.sin_zero,0,8);

	//Associação da porta
	if(bind(localSocket, (struct sockaddr *)&local, sizeof(local)) == -1)
		errorBind();
	
	//Inicio da escuta
	if(listen (localSocket, BACKLOG) == -1)
		errorListen();
	
	structSize = sizeof(struct sockaddr_in);
	
	while(1){
		//Agurda um processo conectars-se
		remoteSocket = accept(localSocket, (struct sockaddr *)&remote, &structSize);
		
		//Após a conxão ser aceita, o processo servidor é duplicado
		pid = fork();
		if(pid == 0){
			
				//Alocação de memória necessária
				bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));
				_bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));	
				msgContent = (char*) calloc (MAXALLOC, sizeof(char));			
			
				fluxo = 0;
				while(!fluxo){	
					recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
					strcpy(_bufferRcv, bufferRcv);
					
					//Após a conexão de um cliente, a primeira mensagem que o servidor espera é do tipo USERNAME,
					//caso contrário o processo servidor é finalizado
					if(checkKindMessage(_bufferRcv,1) == USERNAME){
						//Resgata o conteudo da mensagem
						strcpy(_bufferRcv, bufferRcv);  		
						msgContent = checkMessage(_bufferRcv);
						
						//Verifica se o userName é válido
						if(!checkUserName(msgContent)){
							
								//Se o userName é válido o servidor guarda esse nome para o processo corrente identificar a qual usuário está associado
								strcpy(userName,msgContent);
							
								//Insere o usuário na lista de usuários ativos passando como parâmetros o seu nome e endereço
								insertUser(msgContent,inet_ntoa(remote.sin_addr));
								
								//Informa ao cliente que ele foi conectado		   
								send(remoteSocket,generateMessage("",CONNECTED,1),MAXDATASIZE,0);	
								fluxo = 1;
							}else{
							
								//Sinaliza que o nome de usuário é inválido
								send(remoteSocket,generateMessage("",INVALIDUSERNAME,1),MAXDATASIZE,0);
								fluxo = 0;
							}
					}else{
						close(remoteSocket);
						return 0;
					}
				}
			
			fluxo = 0;	
			while(!fluxo){
				
				//Recebe uma mensagem e guarda o estado de atividade do cliente
				int isActive = recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
				strcpy(_bufferRcv, bufferRcv); 		
				
				//Verifica o tipo da mensagem
				msgKind = checkKindMessage(_bufferRcv,1);
				strcpy(_bufferRcv, bufferRcv);  		
				msgContent = checkMessage(_bufferRcv);
				
				//Se o estado de conexão é ativo
				if(isActive){
					//Trata as mensagem de acordo com o seu tipo
					switch(msgKind){
						//ACTIVEUSERS: O servidor envia para o cliente a lista de usuários ativos
						case ACTIVEUSERS:{
							int i = 0;
							_users = checkActiveUsers();	
							for(i=0;i<_users.size;i++){
								send(remoteSocket,generateMessage(_users.name[i],USERNAME,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						}
						//MESSAGECHAT: O servidor armazena a mensagem enviada pelo cliente	
						case MESSAGECHAT:{
							putMessageChatInLog(userName, msgContent);
							break;
						//UPDATECHAT: O servidor retorna as mensagens direcionadas ao cliente 	
						}case UPDATECHAT:{
							int i = 0;
							_messages = checkLog(userName);
							for(i=0;i<_messages.size;i++){
								send(remoteSocket,generateMessage(_messages.content[i],MESSAGECHAT,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						//CLOSE: O servidor fecha a conexão 	
						}case CLOSE:{
							removeUser(userName);
							deleteUserFiles(userName);
							close(remoteSocket);
							
							free(bufferRcv);
							free(_bufferRcv);
							free(msgContent);
							return 0;
						}
					
					}
				}else{
					removeUser(userName);
					deleteUserFiles(userName);
					close(remoteSocket);
					break;
				}
				
				
			}
			
		free(bufferRcv);
		free(_bufferRcv);
		free(msgContent);	
		break;
		}		
	}
	
	return 0;
}
Example #9
0
void GameConversations::update(bool flag) {
	// Only need to proceed if there is an active conversation
	if (!active())
		return;

	ConversationVar &var0 = _runningConv->_cnd._vars[0];

	switch (_currentMode) {
	case CONVMODE_0:
		assert(var0.isNumeric());
		if (var0._val < 0) {
			if (_vm->_game->_scene._frameStartTime >= _startFrameNumber) {
				removeActiveWindow();
				if (_heroTrigger) {
					_vm->_game->_scene._action._activeAction._verbId = _verbId;
					_vm->_game->_trigger = _heroTrigger;
					_vm->_game->_triggerMode = _heroTriggerMode;
					_heroTrigger = 0;
				}

				_currentMode = CONVMODE_STOP;
			}
		} else {
			bool isActive = nextNode();
			_currentNode = var0._val;

			if (isActive) {
				_verbId = _runningConv->_data._nodes[_currentNode]._index;
				_vm->_game->_scene._action._activeAction._verbId = _verbId;
				_vm->_game->_scene._action._inProgress = true;
				_vm->_game->_scene._action._savedFields._commandError = false;
				_currentMode = CONVMODE_1;
			} else {
				_currentMode = generateMenu();
			}
		}
		break;

	case CONVMODE_1:
		if (flag)
			_currentMode = CONVMODE_3;
		break;

	case CONVMODE_2:
		if (flag) {
			_vm->_game->_player._stepEnabled = false;
			_verbId = _vm->_game->_scene._action._activeAction._verbId;

			if (!(_runningConv->_cnd._entryFlags[_verbId] & ENTRYFLAG_2))
				flagEntry(CMD_HIDE, _verbId);

			removeActiveWindow();
			_vm->_game->_scene._userInterface.emptyConversationList();
			_vm->_game->_scene._userInterface.setup(kInputConversation);
			_personSpeaking = 0;
			executeEntry(_verbId);

			ConvDialog &dialog = _runningConv->_data._dialogs[_verbId];
			if (dialog._speechIndex) {
				_runningConv->_cnd._messageList3.clear();
				_runningConv->_cnd._messageList3.push_back(dialog._speechIndex);
			}

			generateText(dialog._textLineIndex, _runningConv->_cnd._messageList3);
			_currentMode = CONVMODE_0;

			if (_heroTrigger) {
				_vm->_game->_scene._action._activeAction._verbId = _verbId;
				_vm->_game->_trigger = _heroTrigger;
				_vm->_game->_triggerMode = _heroTriggerMode;
				_heroTrigger = 0;
			}
		}
		break;

	case CONVMODE_3:
		if (_vm->_game->_scene._frameStartTime >= _startFrameNumber) {
			removeActiveWindow();
			_personSpeaking = 0;
			executeEntry(_verbId);
			generateMessage(_runningConv->_cnd._messageList1, _runningConv->_cnd._messageList3);
		
			if (_heroTrigger && _popupVisible) {
				_vm->_game->_scene._action._activeAction._verbId = _verbId;
				_vm->_game->_trigger = _heroTrigger;
				_vm->_game->_triggerMode = _heroTriggerMode;
				_heroTrigger = 0;
			}

			_currentMode = CONVMODE_4;
		}
		break;

	case CONVMODE_4:
		if (_vm->_game->_scene._frameStartTime >= _startFrameNumber) {
			removeActiveWindow();
			_personSpeaking = _speakerVal;

			generateMessage(_runningConv->_cnd._messageList2, _runningConv->_cnd._messageList4);

			if (_interlocutorTrigger && _popupVisible) {
				_vm->_game->_scene._action._activeAction._verbId = _verbId;
				_vm->_game->_trigger = _interlocutorTrigger;
				_vm->_game->_triggerMode = _interlocutorTriggerMode;
				_interlocutorTrigger = 0;
			}
		}
		break;

	case CONVMODE_STOP:
		stop();
		break;

	default:
		break;
	}

	warning("TODO: GameConversations::update");
}
void HistoryScr::meteorShower(float dt) {
	CCLOG("%s \n", "Meteor Shower");
	generateMessage(2);
	generateMeteors();

}