Beispiel #1
0
void	Client::seekParty()
{
  _seek = true;
  std::stringstream str;

  if (_lvl < 4)
    _partySize = 1;
  else if (_lvl < 6)
    _partySize = 3;
  else if (_lvl < 8)
    _partySize = 5;
  else
    _partySize = 0;

  str << "broadcast " << _id << " seek " << _lvl << "\n";
  while (_party != true || (_teammate.size() < _partySize && _leader == true))
    {
      checkTime();
      
      _lastCommand = BASIC;
      writeToSocket(str.str());
      
      if (_party != true || (_teammate.size() < _partySize && _leader == true))
      	{
      	  forkUntil(_time - 100);
      	  searchFood(_time + 100);
      	}
      _accept = false;
      _invite = false;
    }
}
Beispiel #2
0
void	Client::defineTime()
{
  _lastCommand = INVENTORY;
  writeToSocket("inventaire\n");
  
  parseInventory();
  _time = (_inventory[0] - 1) * 126;
  refreshTime();
}
Beispiel #3
0
enum Client::e_step Client::sendTeamName(std::string const &buffer)
{
  if (buffer == "BIENVENUE") {
    return Client::WELCOME_STEP;
  }

  writeToSocket(_teamName + "\n");
  return Client::DATA_STEP;
}
Beispiel #4
0
void GameState::send(Protocol::RequestType type, const QByteArray& bytes)
    throw (Protocol::SendingForbidden, Protocol::RequestTypeForbidden)
{
    if ((type != Protocol::FLEET_INSTALLED) && (type != Protocol::TURN_MADE) &&
            (type != Protocol::CHAT_MESSAGE) && (type != Protocol::PLAYER_QUIT))
    {
        throw Protocol::RequestTypeForbidden();
    }
    writeToSocket(type, bytes);
}
Beispiel #5
0
void tcpConnectionListenerRunThread(TcpConnection tcpConnection){
	TcpConnectionInternal* internal=(TcpConnectionInternal*)tcpConnection;
	//Declaring proc    ess variables.
	int size ;
	void* buffer;
        void *commandBuffer;
	int commandSize;
	int currentSize;
	int tempSize=0;
        int result;
	while(internal->active==TRUE){
                size=0;
                while(size<SIZE_OF_INT){
                        tempSize=read(internal->sockfd,&commandSize+size, SIZE_OF_INT-size);
                        if(tempSize<=0){
                                internal->active=FALSE;
                                      distributionManagerHandleTcpConnectionListenerFailure(internal->distributionManager,internal,internal->coreManagerId);
                                return;
                        }
                        size +=tempSize;
                }
                commandSize=htonl(commandSize);
                buffer=memoryAlloc(commandSize-SIZE_OF_INT);
                currentSize=0;
                while(currentSize<commandSize-SIZE_OF_INT){
                        currentSize+=read(internal->sockfd,buffer+currentSize, MIN(MAX_TCP_MESSAGE_SIZE,commandSize-currentSize-SIZE_OF_INT));
                        if(currentSize<=0){
                                internal->active=FALSE;
                                distributionManagerHandleTcpConnectionListenerFailure(internal->distributionManager,internal,internal->coreManagerId);
                                memoryFree(buffer);
                                return;
                        }
                }
                Command command=commandDeSerialize(buffer,commandSize-SIZE_OF_INT);
                commandPush(command,IP,STRING,internal->remoteIp,internal->remoteIpLenght);
                commandPush(command,PORT,INTEGER,&internal->remotePort);
                memoryFree(buffer);
                // handle message
                distributionManagerConsumeTcp(internal->distributionManager,command);
                // Create the result message and send it to client
                commandSize=commandSerialize(command,&commandBuffer);
                result=writeToSocket(internal->sockfd,commandBuffer,commandSize);
                memoryFree(commandBuffer);
                if(result<0){
                        internal->active=FALSE;
                        distributionManagerHandleTcpConnectionListenerFailure(internal->distributionManager,internal,internal->coreManagerId);
                        return;
                }
                // Delete all none model or none atomic commands
                if(commandIsDeleteOnExit(command)==TRUE){
                    commandFree(command);
                }
	}
        internal->readyForCleanup+=LISTENER_READY_FOR_CLEANUP;
}
Beispiel #6
0
void pipeline::sendResponse()
{
    this->preSendResponse();
    
    std::map<std::string, std::string>::const_iterator ite;
    
    ite = this->_response->getHeaders().begin();
    std::ostringstream oss;
    oss << "HTTP/1.1 " << this->_response->getStatusCode() << " " << this->_response->getReasonPhrase() << "\n";
    writeToSocket(oss.str(), this->_client->getSocket());
    while (ite != this->_response->getHeaders().end())
    {
        writeHeaderToSocket(ite->first, ite->second, this->_client->getSocket());
        ++ite;
    }
    writeToSocket("\n", this->_client->getSocket());
    writeToSocket(this->_response->getBody(), this->_client->getSocket());
    writeToSocket("\n", this->_client->getSocket());
    //end
}
Beispiel #7
0
int tcpConnectionSend(TcpConnection tcpConnection,Command command){
    TcpConnectionInternal* internal=(TcpConnectionInternal*)tcpConnection;
    if(internal->active==FALSE){
        return;
    }
    void *commandBuffer;
    int commandSize=commandSerialize(command,&commandBuffer);
    int result = writeToSocket(internal->sockfd,commandBuffer,commandSize);
    memoryFree(commandBuffer);
    return result;
}
Beispiel #8
0
int ServerSocket::listenOnSocket()
{
	int listenErr = listen(this->sockfd, BACKLOG);
	if (listenErr != 0) {
		printf("\nSocket Listen FAILED! %d\n", errno);
		return cleanup();
	}
	printf("\nListening on %d...", PORT);
	acceptConnection();
	printf("\nConnection Accepted!");
	char *buf = new char[128];
	char *start = buf;
	int len = readSocket(buf);
	printf("\nReceived %d bytes", len);
	printf("\nReceived %s", start);
	writeToSocket("RESPONSE");
	return 0;
}
Beispiel #9
0
//Tx thread function
void *AgentTxThread(void *arg)
{
	int errorReply = 0;

	int checksum;
	uint8_t msgSequence[MAX_AGENT_CONNECTIONS];

	for (int i=0; i<MAX_AGENT_CONNECTIONS; i++) msgSequence[i] = 0;

	//loop
	while (1)
	{
		//wait for next message
		psMessage_t *txMessage = GetNextMessage(&agentQueue);

		for (int i=0; i<MAX_AGENT_CONNECTIONS; i++)
		{

			if (connected[i])
			{

    			pthread_mutex_lock(&agentMtx);

				int socket = txSocket[i];

				//send STX
				writeToSocket( socket, STX_CHAR, &checksum, &errorReply);
				checksum = 0; //checksum starts from here
				//send header
				writeToSocket( socket, txMessage->header.length, &checksum, &errorReply);
				writeToSocket( socket, ~txMessage->header.length, &checksum, &errorReply);
				writeToSocket( socket, msgSequence[i]++, &checksum, &errorReply);
				writeToSocket( socket, txMessage->header.source, &checksum, &errorReply);
				writeToSocket( socket, txMessage->header.messageType, &checksum, &errorReply);
				//send payload
				uint8_t *buffer = (uint8_t *) &txMessage->packet;
				uint8_t size = txMessage->header.length;

				if (size > sizeof(psMessage_t) - SIZEOF_HEADER)
				{
					size = txMessage->header.length = sizeof(psMessage_t) - SIZEOF_HEADER;
				}

				while (size) {
					writeToSocket( socket, *buffer, &checksum, &errorReply);
					buffer++;
					size--;
				}
				//write checksum
				writeToSocket( socket, (checksum & 0xff), &checksum, &errorReply);

				if (errorReply != 0)
				{
					ERRORPRINT("agent: Tx send error: %s\n", strerror(errno));
					AGENTsendErrors;
					close(socket);
					txSocket[i] = -1;
					connected[i] = false;
				}
				else
				{
					DEBUGPRINT("agent: %s message sent\n", psLongMsgNames[txMessage->header.messageType]);
					AGENTmessagesSent++;
					if (psDefaultTopics[txMessage->header.messageType] == LOG_TOPIC)
					{
						switch (txMessage->logPayload.severity)
						{
						case SYSLOG_INFO:
							agentInfo--;
							break;
						case SYSLOG_WARNING:
							agentWarning--;
							break;
						case SYSLOG_ERROR:
							agentError--;
						default:
							break;
						}
					}
				}

    			pthread_mutex_unlock(&agentMtx);

			}
		}
		DoneWithMessage(txMessage);
	}
	return 0;
}
int main(int argc, char *argv[])
{
	int serverSockId, clientSockId;
	struct sockaddr_in serverSockAddr,clientSocAddr;
	int status,serverStorageSize,i;
	char messageBuffer[4096];
	int bytesRead;
	struct sockaddr_storage serverStorage;
	

	/* 
		We will generate a socket for our usage.
		A descriptor
	*/
	serverSockId = socket(
		AF_INET, 
		SOCK_STREAM, 
		0
	);
	if(serverSockId == -1)
	{
		printf("Something went wrong with socket generation.\nPlease try again :P \n");
		return 0;
	}
	serverSockAddr.sin_family = AF_INET;
	serverSockAddr.sin_port = htons(atoi(argv[1]));
	serverSockAddr.sin_addr.s_addr = INADDR_ANY;
	

	/*
		We'll bind the descriptor with the socket.
		From now on we can refer to descriptor for the coket
	*/
	status = bind(
		serverSockId, 
		(struct sockaddr *)&serverSockAddr, 
		sizeof(serverSockAddr)
	);
	if(status == -1)
	{
		fprintf(stderr,"This socket port seems occupied!\n");
		return 0;
	}
	

	/*
		We'll start listenig through this socket, 
		whether anyone wants to connect.
	*/
	int listenStatus = listen(serverSockId , 3);
	if(listenStatus < 0)
	{
		fprintf(stderr,"I can't listen to this port right now. Please try again!\n");
		return 0;
	}
	serverStorageSize = sizeof(serverStorage);
	
	/*
		This is a persistence loop to facilitate
		for multiple connections - one by one.
	*/
	while(1)
	{
		/*
			We accept the connection request sent by client
			and receive a descriptor for the clients socket.
		*/
		clientSockId = accept(
			serverSockId, 
			(struct sockaddr *)&serverStorage,
			&serverStorageSize
		);
		if(clientSockId < 0)
		{
			printf("I can't accept this socket\n");
			return 0;
		}

		/*
			Here's a pretty dumb and awesome thing we'll do.
			We'll treat the socket as a 'File'. Yes as a 'File'.
			We'll use two files. One for writng and the other for reading.
			We can generate the file pointers using fdopen. Read Man pages
		*/		
		FILE *writeSocket = fdopen(clientSockId, "w");
		FILE *readSocket = fdopen(dup(clientSockId),"r");		
		
		
		/*
			Empty the buffer and send a welcome message.
		*/
		memset(messageBuffer,0,4096);
		strcpy(messageBuffer, "Server: Welcome - We just connected\n");
		writeToSocket(messageBuffer,writeSocket);
		

		while(1)
		{
			/*
				This loop is ensure the connection with the same
				client, unless the client itself closes connection.
			*/

			/*
				We read message from client( A File name)
			*/
			memset(messageBuffer,0,4096);
			bytesRead = fread(
				messageBuffer,
				1, 
				4096, 
				readSocket
			);
			if(bytesRead == 0)
			{
				break;
			}

			printf("The client needs this file: %s\n", messageBuffer);
			
			/*
				Open the file required by the client
			*/
			FILE *file;
			file = fopen(messageBuffer,"r");
			
			if(file == NULL)
			{
				/*
					If the clients request is erroneous, we
					need to tell the client its erroneous.
				*/
				memset(messageBuffer,0,4096);
				strcpy(messageBuffer,"Server: Such file doesn't exist\n");
				intTostr(333);
				snprintf(messageBuffer+4091, 5, "%s",intstr); 	
				writeToSocket(messageBuffer,writeSocket);
				continue;
			}

			memset(messageBuffer,0,4096);
			strcpy(messageBuffer,"Server: I received your request\n\tHere are the File contents:");
			intTostr(24);
			snprintf(messageBuffer+4091, 5, "%s",intstr);
			writeToSocket(messageBuffer,writeSocket);
			
			while(1)
			{
				/*
					This is a control loop for file reading.
					We read from a large file block by block into
					buffer and then transmit it.

				*/
				memset(messageBuffer,0,4096);
				bytesRead = fread(messageBuffer,1,4091,file);
				if(!bytesRead)
				{
					/*
						If EOF of file is reached, fread stops reading.
						So we send our custom EOF in the message buffer
						and then start listening for new message by breaking
						of this loop.
					*/
					memset(messageBuffer,0,4096);
					strcpy(messageBuffer,"<---EOF--->");
					intTostr(11);
					snprintf(messageBuffer+4091, 5, "%s",intstr);
					writeToSocket(messageBuffer,writeSocket);
					break;
				}
				intTostr(bytesRead);
				/*
					We did something really cool here.
					We send the client how many bytes we read from file 
					as a integer string in the last 5 bytes.
					So the client needs to just read those many bytes, 
					although we send 4096 bytes through fwrite.
				*/
				snprintf(messageBuffer+4091, 5, "%s",intstr);
				writeToSocket(messageBuffer,writeSocket);
			}
		}
		fclose(readSocket);
		fclose(writeSocket);
	}
	return 0;
}
void mdtTcpSocketThread::run()
{
  Q_ASSERT(pvPort != 0);

  mdtTcpSocket *socket;

  pvPort->lockMutex();
  // Init write frame
  pvWriteCurrentFrame = 0;
  // Get a RX frame
  pvReadCurrentFrame = getNewFrameRead();
  if(pvReadCurrentFrame == 0){
    mdtError e(MDT_TCP_IO_ERROR, "No frame available in read frames pool, stopping thread", mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread");
    e.commit();
    pvRunning = false;
    pvPort->unlockMutex();
    return;
  }
  // Alloc the local buffer
  pvReadBufferSize = pvReadCurrentFrame->capacity();
  pvReadBuffer = new char[pvReadBufferSize];
  if(pvReadBuffer == 0){
    mdtError e(MDT_TCP_IO_ERROR, "Cannot allocate memory for local read buffer" , mdtError::Error);
    MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread");
    e.commit();
    pvRunning = false;
    pvReadBufferSize = 0;
    pvPort->unlockMutex();
    return;
  }
  //bufferCursor = buffer;
  // Create a Tcp socket
  pvSocket = new QTcpSocket;
  Q_ASSERT(pvSocket != 0);
  // We must pass this socket object to pvPort
  // pvPort must be a instance of mdtTcpSocket
  socket = dynamic_cast<mdtTcpSocket*>(pvPort);
  Q_ASSERT(socket != 0);
  socket->setThreadObjects(pvSocket, this);
  // Set the running flag
  pvRunning = true;

  // Run...
  while(1){
    // Read thread state
    if(!pvRunning){
      break;
    }
    // Check if a connection was requested
    if(pvPeerPort == 0){
      socket->waitForNewTransaction();
    }
    if(pvSocket->state() == QAbstractSocket::ConnectedState){
      // Wait on write ready event
      if(!pvPort->waitEventWriteReady()){
        emit(errorOccured(MDT_TCP_IO_ERROR));
        /// NOTE: sleep ?
      }
      // Read thread state
      if(!pvRunning){
        break;
      }
      // **********************
      // Event occured, send the data to port - Check timeout state first
      if(!pvPort->writeTimeoutOccured()){
        // Write data to send
        writeToSocket();
      }
      // Wait until data is available for read
      if(!pvPort->waitForReadyRead()){
        emit(errorOccured(MDT_TCP_IO_ERROR));
        /// NOTE: sleep ?
      }
      // Read thread state
      if(!pvRunning){
        break;
      }
      // **********************
      // Event occured, get the data from port - Check timeout state first
      if(!pvPort->readTimeoutOccured()){
        // We received data , read it
        readFromSocket();
      }
    }else{
      // Try to (Re-)connect
      if(!reconnectToHost()){
        qDebug() << "TCP THD: SIGNAL: Cannot reconnect - Retry at next transaction ...";
        socket->waitForNewTransaction();
      }
    }
  }

  // Put current frame into pool
  if(pvReadCurrentFrame != 0){
    pvPort->readFramesPool().enqueue(pvReadCurrentFrame);
  }
  // End connection
  if(pvSocket->state() == QAbstractSocket::ConnectedState){
    pvSocket->disconnectFromHost();
    if(pvSocket->state() != QAbstractSocket::UnconnectedState){
      // Wait on disconnected
      if(!pvSocket->waitForDisconnected(500)){
        mdtError e(MDT_TCP_IO_ERROR, "Cannot wait for disconnected" , mdtError::Error);
        e.setSystemError(pvSocket->error(), pvSocket->errorString());
        MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread");
        e.commit();
      }
    }
  }
  // Free memory
  Q_ASSERT(pvReadBuffer != 0);
  delete pvReadBuffer;

  pvPort->unlockMutex();
}
void ChatRoomBroadCastSocket::sendPrivateChat(QString identifier)
{
    writeToSocket(PRIVATECHAT, identifier);
}
void ChatRoomBroadCastSocket::sendParticipantLeft()
{
    writeToSocket(PARTICIPANTLEFT);
}
void ChatRoomBroadCastSocket::sendNewParticipant()
{
    writeToSocket(NEWPARTICIPANT);
}
void ChatRoomBroadCastSocket::sendMessage(QString message)
{
    writeToSocket(MESSAGE, message);
}
void ChatRoomBroadCastSocket::run()
{
    writeToSocket(NEWPARTICIPANT);
}