示例#1
0
int NetworkHandler::meetClient(int pSocket)
{
    _runClient = 0; /* Verificador del ciclo. */   
    _exitCode = 0; /* Código de salida por defecto */         

    while (!_runClient)
    {
        /* Setear el buffer a cero. */
        memset(_inBuffer, 0, BUFFERSIZE);
        /* Recivimos la información y al mismo tiempo evaluamos si llego correctamente. */
        if ((_byteCount = recv(pSocket, _inBuffer, BUFFERSIZE, 0))== -1)
        {
            Error(5, "No se pudo recibir la información.");
        }
        if(_byteCount == 0)
        {
            std::cout << "!ATENCIÓN! El cliente " << inet_ntoa(_clientIP.sin_addr) <<  " se ha desconectado inesperadamente, conexión perdida." << std::endl;
            _runClient = 1;
        }
        /* Se convierte el _inBuffer de char a string para un manejo más fácil. */
        std::string inMessageBuffer = _inBuffer;

        /* Se envia el mensaje a otro método para su posterior evaluación. */
        inMessage(inMessageBuffer, pSocket);
    }
    close(pSocket); /* Se cierra la conexión del cliente. */
    return _exitCode; /* Retorna el codigo de salida */
}
示例#2
0
    int WebSocketQueue::callback(libwebsocket_context *context, libwebsocket *wsi,
                                 LibWebsocketsCallbackReasonBoxed const& reasonBoxed,
                                 void *user, void *in, size_t len)
    {
        WebSocketQueue *self = (WebSocketQueue*)libwebsocket_context_user(context);
        PerSession *perSession = (PerSession*)user;
        libwebsocket_callback_reasons reason = reasonBoxed.value;

        // reason for callback
        switch (reason) {
        case LWS_CALLBACK_FILTER_NETWORK_CONNECTION: {
            if (self->sessions_.size() >= self->maxSessionCount_) {
                GATEY_LOG("not accepting connection because already connected");
                return -1;
            }
            break;
        }
        case LWS_CALLBACK_ESTABLISHED:
            *perSession = PerSession(self->nextUniqueSessionId_);
            self->nextUniqueSessionId_++;
            self->sessions_.insert(perSession->sessionId);
            if (self->sessions_.size() > self->maxSessionCount_) {
                GATEY_LOG("connection established but will be canceled" + std::to_string(perSession->sessionId));
                return -1;
            }

            GATEY_LOG("connection established" + std::to_string(perSession->sessionId));
            break;
        case LWS_CALLBACK_RECEIVE: {
            char const* bytes = (char const*)in;
            InMessage inMessage(perSession->sessionId, bytes, len);
            self->inMessages_.push_back(std::move(inMessage));

            GATEY_LOG("received message");
            break;
        }
        case LWS_CALLBACK_SERVER_WRITEABLE: {
            //Send messages from the queue
            auto found = self->firstMessageWithDestination(perSession->sessionId);
            if (found == self->outMessages_.end())
                break;
            
            OutMessage& message = *found;
            libwebsocket_write(wsi, (unsigned char*)&message.buffer_[LWS_SEND_BUFFER_PRE_PADDING], message.len_, LWS_WRITE_TEXT);
            
            message.removeDestination(perSession->sessionId);
            self->messageSent_ = true;
            break;
        }
        case LWS_CALLBACK_CLOSED: {
            self->sessions_.erase(perSession->sessionId);
            for(OutMessage& outMessage : self->outMessages_) {
                outMessage.removeDestination(perSession->sessionId);
            }
            
            //TODO: Remove already received messages? no
//            std::remove_if(self->inMessages_.begin(), self->inMessages_.end(),
//                           [sessionId](InMessage const& message)
//            {
//                return message.sessionId_ == sessionId;
//            });
            
            GATEY_LOG("connection closed" + std::to_string(perSession->sessionId));
            break;
        }

        default: break;
        }

        return 0;
    }
示例#3
0
int main(int argc, char* argv[])
{
    (void) argc; // suppress unused parameter warnings
    (void) argv; // suppress unused parameter warnings

	struct sockaddr_in myaddr;	/* our address */
	struct sockaddr_in remaddr;	/* remote address */
	socklen_t addrlen = sizeof(remaddr);		/* length of addresses */
	int recvlen;			/* # bytes received */
	int fd;				/* our socket */
	unsigned char buf[BUFFER_SIZE];	/* receive buffer */

	/* create a UDP socket */

	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("cannot create socket\n");
		return 0;
	}
	
    UdpTransmitSocket transmitSocket( IpEndpointName( SEND_ADDRESS, SEND_PORT ) );
	
	// The buffer out
    char buffer[BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, BUFFER_SIZE );
    
	/* bind the socket to any valid IP address and a specific port */

	memset((char *)&myaddr, 0, sizeof(myaddr));
	myaddr.sin_family = AF_INET;
	myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	myaddr.sin_port = htons(RECEIVE_PORT);

	if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
		perror("bind failed");
		return 0;
	}
	else{ 
		printf("Listening to port %d\n", RECEIVE_PORT);
	}
	
	/* now loop, receiving data and printing what we received */
	for (;;) {
		recvlen = recvfrom(fd, buf, BUFFER_SIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
		if (recvlen > 0) {
			buf[recvlen] = 0;
			
			// retrieving the data from the udp message
			std::string inMessage( buf, buf + sizeof buf / sizeof buf[0] ); // converting the input buffer to a string
			
			// counting the number of semicolons to detect the number of messages in the packet
			int nParams = std::count(inMessage.begin(), inMessage.end(), ';')-2;

			for(int i=0; i<nParams; i++){
				std::string oscAddress = OSC_BASE_ADDRESS;
				oscAddress.append(inMessage.substr(0,inMessage.find(":")));
				std::string oscValueString = inMessage.substr(inMessage.find(":")+1,inMessage.find(";")-inMessage.find(":")-1);
				// making sure that the received message is valid
				if(!std::all_of(oscValueString.begin(), oscValueString.end(), ::isdigit)){
					float oscValue = stof(oscValueString);
					//printf("Rec: %s: ",oscAddress.c_str());
					//printf("%f\n", oscValue);
					inMessage = inMessage.substr(inMessage.find("\n")+1,inMessage.find(";;")-inMessage.find("\n"));
			
					// formating and sending the OSC message
		    		p.Clear();
		    		p << osc::BeginMessage(oscAddress.c_str())
		        	    << oscValue << osc::EndMessage;
		    		transmitSocket.Send( p.Data(), p.Size() );
		    	}
		    	else printf("Dropped message\n");
			}
		}
	}
	/* never exits */
}
void ThousandClientDataParser::incomingData()
{
    QueryStruct query;
    quint16 blockSize = 0;
    QTcpSocket *socket = workClient->connection;
    QDataStream stream(socket);
    quint16 requestSize = sizeof(QueryStruct) - 2 * sizeof(quint16);
    QByteArray incomingRequest;
    while (requestSize) {
        blockSize = socket->bytesAvailable();
        if (blockSize > requestSize) blockSize = requestSize;
        if (!blockSize) {
            emit(workClient->erorText("Invalid size of query"));
            break;
        }
        char *buffer = new char[blockSize];
        stream.readRawData(buffer, blockSize);
        incomingRequest += QByteArray::fromRawData(buffer, blockSize);
        requestSize -= blockSize;
        blockSize = 0;
        delete []buffer;
    }
    QDataStream reader(incomingRequest);
    reader>>query;  //Извлекаем структуру с запросом из входящего потока


    QByteArray data;
    requestSize = query.size;
    while (requestSize) {
        blockSize = socket->bytesAvailable();
        if (blockSize > requestSize) blockSize = requestSize;
        if (!blockSize) {
            emit(workClient->erorText("Invalid size of query"));
            break;
        }
        char *buffer = new char[blockSize];
        stream.readRawData(buffer, blockSize);
        data += QByteArray::fromRawData(buffer, blockSize);
        requestSize -= blockSize;
        blockSize = 0;
        delete []buffer;
    }

    switch(query.type)
    {
    case REGISTER:
        inRegistration(data);
        break;
    case AUTHORIZATION:
        inAuthorization(data);
        break;
    case MESSAGE:
        inMessage(data);
        break;
    case NEWGAME:
        inNewGame(data);
        break;
    case CONNECTGAME:
        inConnectToGame(data);
        break;
    case DISCONNECTGAME:
        inDisconnectGame(data);
        break;
    case STARTGAME:
        inStartGame(data);
        break;
    case CANCELGAME:
        inCancelGame(data);
        break;
    case FINISHGAME:
        inFinishGame(data);
        break;
    case LISTALLCURRENTGAME:
        inListAllGame(data);
        break;
    case LISTALLNEWGAME:
        inListAllNewGame(data);
        break;
    case TOTALSTATISTICS:
        inTotalStatistics(data);
        break;
    case PLAYERSTATISTICS:
        inPlayerStatistics(data);
        break;
    case MOVE:
        inMove(data);
        break;
    }
}