void DSPEngine::handleSetSource(SampleSource* source)
{
	gotoIdle();
	if(m_sampleSource != NULL)
		disconnect(m_sampleSource->getSampleFifo(), SIGNAL(dataReady()), this, SLOT(handleData()));
	m_sampleSource = source;
	if(m_sampleSource != NULL)
		connect(m_sampleSource->getSampleFifo(), SIGNAL(dataReady()), this, SLOT(handleData()), Qt::QueuedConnection);
	generateReport();
}
示例#2
0
/**
 * Client Process
 * Runs the main checks for new packets
 *
 * Return's a ByteBuffer is new data was recieved
 */
ByteBuffer* ProxyClient::clientProcess() {
	size_t dataLen = SO_RCVBUF;
	char *pData = new char[dataLen];
	ByteBuffer *retBuf = NULL;
    
	// Receive data on the wire into pData
	/* TODO: Figure out what flags need to be set */
	int flags = 0; 
	ssize_t lenRecv = recv(clientSocket, pData, dataLen, flags);
    
	// Act on return of recv. 0 = disconnect, -1 = no data, else the size to recv
	if(lenRecv == 0) {
		// Server closed the connection
		printf("ProxyClient: Socket closed by server, disconnecting\n");
		clientRunning = false;
	} else if(lenRecv == -1) {
		// No data to recv. Empty case to trap
	} else {
		printf("ProxyClient: Recieved data of size %u\n", lenRecv);
		// Usable data was received. Create a new instance of a ByteBuffer, pass it the data from the wire
        ByteBuffer *buf = new ByteBuffer((byte *)pData, (unsigned int)lenRecv);

		// Pass the new ByteBuffer into the handler, return the output of the handler
		retBuf = handleData(buf);
	}

	if(pData != NULL)
		delete [] pData;

	return retBuf;
}
示例#3
0
文件: proj.c 项目: noamshevach/tosite
/**
 * This function returns the next line on file.
 * fp - the file.
 * ln - empty array , will contain the line.
 * stepOneEnd - boolean pointer. (is EOF?)
 */
void getLine(FILE* fp, line ln[], bool* stepOneEnd)
{
	string startline = malloc(sizeof(char) * maxLineLength);
	int idx = 0, i = 1;
	fgets(startline, maxLineLength, fp);
	while(idx < strlen(startline) && i < lineVar){
		readNextWord(startline, &idx, stepOneEnd, (ln + i));
		if(strcmp(ln[i].word, "EMPTY") == 0)
			break;
		if(i == 1 && isLabel(ln[i])){
			ln[i].word[idx - 2] = (char)'\0';
			i--;
			ln[i].word = malloc(sizeof(string) * 100);
			strcpy(ln[i].word, ln[i + 1].word);
			ln[i].wordIdx = ln[i + 1].wordIdx;
			free(ln[i + 1].word);
			ln[i + 1].word = "NULL";
		}
		if(strcmp(ln[i].word, ".data") == 0){
			ln[i].wordIdx = handleData(idx, startline, stepOneEnd);
			break;
		}
		if(idx < strlen(startline))
			ln[i + 1].wordIdx = ln[i].wordIdx;
		i++;
	}
	free(startline);
}
QWaveDecoder::QWaveDecoder(QIODevice *s, QObject *parent):
    QIODevice(parent),
    haveFormat(false),
    dataSize(0),
    source(s),
    state(QWaveDecoder::InitialState),
    junkToSkip(0),
    bigEndian(false)
{
    open(QIODevice::ReadOnly | QIODevice::Unbuffered);

    if (enoughDataAvailable())
        QTimer::singleShot(0, this, SLOT(handleData()));
    else
        connect(source, SIGNAL(readyRead()), SLOT(handleData()));
}
示例#5
0
int Iterative_Server::run()
{
	int retsock;
	if( (retsock=init())<=0)
	{
		outerr("server init error, exit");
		exit(0);
	}

	fprintf(stdout, "the server run:\n");

	
	SocketStream ss;
	for(;;)
	{

		acceptor(retsock,ss);
		if(waitfor_multievent()==-1)
			return -1;
		if(handleConnection()==-1)
			return -1;
		if(handleData(ss)==-1)
			return -1;
	}




}
void CDataHandler::run()
{
	detach();  // 分离自己,线程结束则自动释放资源
	
	const int waitMillisecond = 1000 * 1;  // 无数据处理时等待的时间,1毫秒
	NetPkgHeader userPkgHeader(0, MSG, 0);  // 用户数据包头
	Connect* msgConnList = NULL;
	while (m_status == running)
	{
		m_connMgr->waitConnecter();  // 等待连接处理线程处理完
		msgConnList = m_connMgr->getMsgConnectList();
		if (msgConnList != NULL) // 处理连接数据
		{
			if (handleData(msgConnList, userPkgHeader) < 1) usleep(waitMillisecond);  // 无数据处理则等待让出cpu
		}
		else if (!readFromLogic(userPkgHeader))
		{
			 usleep(waitMillisecond);  // 无数据处理则等待让出cpu
		}
	}

	// 释放所有连接的写buffer内存块
	msgConnList = m_connMgr->getMsgConnectList();
	while (msgConnList != NULL)
	{
	    releaseWriteBuffer(msgConnList);
		msgConnList = msgConnList->pNext;
	}
	
	// 终止线程运行
	m_status = stopted;
	stop();
}
bool DDAProtocol :: exec()
{
  int errorCount = ERROR_COUNT;
  while(!m_terminated)
  {
    if(rxPacket())
    {
      errorCount = ERROR_COUNT;
      unsigned txSize = m_txData.size();
      if(!txSize)
      {
        //Send ACK
        unsigned char tx = ACK;
        serial_write(m_serial, &tx, 1);
      }
      else
      {
        txPacket();
        waitAck();
      }
      handleData(m_rxData);
      m_rxData.clear();
    }
    else
    {
      if(--errorCount <= 0)
        return false;
    }
  }
  return true;
}
QT_BEGIN_NAMESPACE

WaveDecoder::WaveDecoder(QIODevice *s, QObject *parent):
    QIODevice(parent),
    haveFormat(false),
    dataSize(0),
    remaining(0),
    source(s)
{
    open(QIODevice::ReadOnly | QIODevice::Unbuffered);

    if (source->bytesAvailable() >= qint64(sizeof(CombinedHeader) + sizeof(DATAHeader) + sizeof(quint16)))
        QTimer::singleShot(0, this, SLOT(handleData()));
    else
        connect(source, SIGNAL(readyRead()), SLOT(handleData()));
}
void Interpreter::handleResponse(const void *args[])
{
    // strip off response, add to print string
    m_print = "response: " +
            QString::number(*(int *)args[0]) + " (0x" + QString::number((uint)*(uint *)args[0], 16) + ") ";

    // render rest of response, if present
    handleData(args+1);
}
示例#10
0
void RobotOpenClass::pollDS() {
    // Process any data sitting in the buffer
    handleData();
  
    //Only allow robot to be enabled if we've received data in the last 250ms and robot is set to enabled
    if (((millis() - _lastUpdate) <= 250) && (millis() > 500)) {  //Robot is disabled for first 500ms of runtime
        _enabled = true;
	}
    else {
        _enabled = false;
    }
}
示例#11
0
/*select the relevant handle*/
void handleGuideline(GuidelineHolder* holder, AssemblyLine* assemblyLine) {
	if (startsWith(assemblyLine->line, STRING_STR)) {
		handleString(holder, assemblyLine);
	}
	else if (startsWith(assemblyLine->line, DATA_STR)) {
		handleData(holder, assemblyLine);
	}
	else if (startsWith(assemblyLine->line, EXTERN_STR)) {
		handleExtern(holder, assemblyLine);
	}
	else if (startsWith(assemblyLine->line, ENTRY_STR)){
		handleEntern(holder, assemblyLine);
	}
}
示例#12
0
// 由逻辑层主动收发消息
ReturnValue CDataHandler::recv(Connect*& conn, char* data, unsigned int& len)
{
	// 1)先过滤掉无效的连接
	while (m_curConn != NULL && m_curConn->logicStatus == ConnectStatus::deleted) m_curConn = m_curConn->pNext;
	Connect* nextConn = (m_curConn != NULL) ? m_curConn->pNext : NULL;  // 必须在wait之前获取,wait之后如果m_curConn被移出队列则next已经为空了
	
	// 2)接着等待连接处理线程处理完
	m_connMgr->waitConnecter();
	if (m_curConn == NULL || m_curConn->readSocketTimes == 0)  // wait之后存在m_curConn可能被连接线程移出队列了
	{
		m_curConn = (nextConn != NULL) ? nextConn : m_connMgr->getMsgConnectList();  // 必须确保连接在队列中,否则会错误、无限循环
		if (m_curConn == NULL) return NotNetData;
	}

	unsigned int curSecs = time(NULL);
	unsigned int dataSize = 0;
	Connect* const beginConn = m_curConn;
	while (true)
	{
		if (m_curConn->connStatus == ConnectStatus::normal && m_curConn->logicStatus == ConnectStatus::normal)
		{
			dataSize = getCanReadDataSize(m_curConn);  // 当前可以从连接读取的数据量
			if (dataSize == 0)
			{
				writeHbRequestPkg(m_curConn, curSecs);  // 发送心跳请求包检查网络连接
			}
			else if (handleData(m_curConn, dataSize, curSecs, len, data))  // 存在数据则读取,写入逻辑层
			{
				conn = m_curConn;
				m_curConn = m_curConn->pNext;  // 切换到下一个连接,以便均衡遍历所有连接
				return OptSuccess;
			}
		}
		
		// 删除销毁已经关闭的连接
		else if (m_curConn->connStatus == ConnectStatus::closed && m_curConn->logicStatus != ConnectStatus::deleted)
		{
			releaseWriteBuffer(m_curConn);
			m_curConn->logicStatus = ConnectStatus::deleted;  // 标志此连接为无效连接,可删除了
		}
		
		m_curConn = (m_curConn->pNext != NULL) ? m_curConn->pNext : m_connMgr->getMsgConnectList();
		if (m_curConn == beginConn) break;  // 回到循环起点了,无可处理的消息
	}
	
	return NotNetData;
}
示例#13
0
文件: Parser.cpp 项目: miyucy/swfmill
void Parser::handleDelimiter(string& tmp) {
	trimString(tmp);
		
	if(insideParams) {
		if(tmp.length() > 0) {
			params.push_back(tmp);
		}
		handleData(outside, params);
		params.clear();
	} else {
		outside = tmp;
	}
	
	insideParams = !insideParams;
	tmp.clear();
	swapDelimiters();
}
示例#14
0
void WaveDecoder::handleData()
{
    if (source->bytesAvailable() < qint64(sizeof(CombinedHeader) + sizeof(DATAHeader) + sizeof(quint16)))
        return;

    source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
    source->read((char*)&header, sizeof(CombinedHeader));

    if (qstrncmp(header.riff.descriptor.id, "RIFF", 4) != 0 ||
        qstrncmp(header.riff.type, "WAVE", 4) != 0 ||
        qstrncmp(header.wave.descriptor.id, "fmt ", 4) != 0 ||
        (header.wave.audioFormat != 0 && header.wave.audioFormat != 1)) {

        emit invalidFormat();
    }
    else {
        DATAHeader dataHeader;

        if (qFromLittleEndian<quint32>(header.wave.descriptor.size) > sizeof(WAVEHeader)) {
            // Extended data available
            quint16 extraFormatBytes;
            source->peek((char*)&extraFormatBytes, sizeof(quint16));
            extraFormatBytes = qFromLittleEndian<quint16>(extraFormatBytes);
            source->read(sizeof(quint16) + extraFormatBytes);   // dump it all
        }

        source->read((char*)&dataHeader, sizeof(DATAHeader));

        int bps = qFromLittleEndian<quint16>(header.wave.bitsPerSample);

        format.setCodec(QLatin1String("audio/pcm"));
        format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setFrequency(qFromLittleEndian<quint32>(header.wave.sampleRate));
        format.setSampleSize(bps);
        format.setChannels(qFromLittleEndian<quint16>(header.wave.numChannels));

        dataSize = qFromLittleEndian<quint32>(dataHeader.descriptor.size);

        haveFormat = true;
        connect(source, SIGNAL(readyRead()), SIGNAL(readyRead()));
        emit formatKnown();
    }
}
示例#15
0
	void FileTransferManager::handleRequest (int32_t friendNum,
			const QByteArray& pkey, uint8_t filenum, uint64_t size, const QString& name)
	{
		const auto toxThread = ToxThread_.lock ();
		if (!toxThread)
		{
			qWarning () << Q_FUNC_INFO
					<< "Tox thread is not available";
			return;
		}

		const auto entry = Acc_->GetByPubkey (pkey);
		if (!entry)
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to find entry for pubkey"
					<< pkey;
			return;
		}

		const auto transfer = new FileTransferIn
		{
			entry->GetEntryID (),
			pkey,
			friendNum,
			filenum,
			static_cast<qint64> (size),
			name,
			toxThread
		};

		connect (this,
				SIGNAL (gotFileControl (qint32, qint8, qint8, QByteArray)),
				transfer,
				SLOT (handleFileControl (qint32, qint8, qint8, QByteArray)));
		connect (this,
				SIGNAL (gotData (qint32, qint8, QByteArray)),
				transfer,
				SLOT (handleData (qint32, qint8, QByteArray)));

		emit fileOffered (transfer);
	}
示例#16
0
void readSocks() //check all the sockets
{
	int x;	    
	
    if (FD_ISSET(sockfd, &readfds))
    {
		handle_new_connection();
    }
	
	
	// Run through our sockets and check to see if anything happened with them
	for (x = 0; x < MAX_USERS; x++) 
    {
		if (FD_ISSET(fd[x], &readfds))
        {
            printf("handling user: %d\n", x);
			handleData(x);
        }
	} 
}
示例#17
0
int CDataHandler::handleData(Connect* msgConnList, NetPkgHeader& userPkgHeader)
{
	unsigned int pkgLen = 0;
	int handledMsgCount = 0;
	unsigned int curSecs = time(NULL);
	unsigned int dataSize = 0;
	Connect* curConn = NULL;
	while (msgConnList != NULL && isRunning())
	{
		if (readFromLogic(userPkgHeader)) ++handledMsgCount;  // 从逻辑层读数据写入对应的连接
		
		curConn = msgConnList;
		msgConnList = msgConnList->pNext;
		
		if (curConn->logicStatus == deleted) continue;  // 忽略无效的连接
		
		if (curConn->connStatus == closed)
		{
			releaseWriteBuffer(curConn);
			curConn->logicStatus = deleted;             // 标志此连接为无效连接,可删除了
			continue;
		}
		
		// 这里等待一下,等待连接处理线程处理完
		// 连接线程删除无效连接,因此等待成功则必须重新取下一个连接,否则如果当前msgConnList为无效连接的话会出错
		if (m_connMgr->waitConnecter()) msgConnList = curConn->pNext;
		
		// 从连接读数据写入逻辑层
		dataSize = getCanReadDataSize(curConn);  // 当前可以从连接读取的数据量
		if (dataSize == 0)
		{
			writeHbRequestPkg(curConn, curSecs);  // 发送心跳请求包检查网络连接
		}
		else if (handleData(curConn, dataSize, curSecs, pkgLen))  // 存在数据则读取,写入逻辑层
		{
			++handledMsgCount;
		}
	}
	
	return handledMsgCount;
}
int IioSensorBase::readEvents(sensors_event_t* data, int count)
{
    if (count < 1)
        return -EINVAL;

    pthread_mutex_lock(&mLock);
    int numEventReceived = 0;

    if (mHasPendingEvent) {
        mHasPendingEvent = false;
        if (mEnabled) {
            mPendingEvent.timestamp = getTimestamp();
            *data = mPendingEvent;
            numEventReceived++;
        }
        goto done;
    }

    iio_event_data const* event;

    while (count && mInputReader.readEvent(mDataFd, &event)) {
        int value;
        if (IIO_EVENT_CODE_EXTRACT_CHAN_TYPE(event->id) == mIioChanType) {
            if (mEnabled && readValue(&value)) {
                handleData(value);
                mPendingEvent.timestamp = event->timestamp;
                *data++ = mPendingEvent;
                count--;
                numEventReceived++;
            }
        }
        mInputReader.next();
    }

done:
    pthread_mutex_unlock(&mLock);
    return numEventReceived;
}
示例#19
0
void DirectHandler::handleValue(const JSONEntity& val)
{
	if (0 == icompare(_key, "action"))
	{
		handleAction(val.toString());
	}
	else if (0 == icompare(_key, "method"))
	{
		handleMethod(val.toString());
	}
	else if (0 == icompare(_key, "data"))
	{
		handleData(val);
	}
	else if (0 == icompare(_key, "type"))
	{
		handleType(val.toString());
	}
	else if (0 == icompare(_key, "tid"))
	{
		handleTID(val.toInteger());
	}
}
//-----------------------------------------------------------------------------
void IoHandler::handlePacket() 
{
    QByteArray *pPacket;

    if (comPort->getThread()->getPacket(&pPacket) > 0)
    {
        unsigned short cmdID;  // Command ID
        //LENGTH(1)-CMD(2)-DATA(....)-FCS(1)
        cmdID = MAKE_WORD_LE(pPacket,1);

        switch (cmdID)
        {
            case SYS_PING_RESPONSE:
				unsigned short profileID;
				profileID= MAKE_WORD_LE(pPacket,3);
				pNodeDb->setProfileID(profileID);
                pingAnswered = true;
                emit pingReceived();
                break;
            case ZB_RECEIVE_DATA_INDICATION:
                handleData(pPacket);
                break;
            default:
                emit unknownMessage();
        }

		if (pLog)
			pLog->enterPacket(pPacket);
        
    }
    else
    {
        emit emptyPacket();
    }
    
}
示例#21
0
ServerSocket::ServerSocket (QObject *parent) : OHSocket(parent), m_adm(false)//, m_ident(false)
{
    connect(this, SIGNAL(dataUnhandled()), this, SLOT(handleData()));
    connect(this, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
}
示例#22
0
bool HTTPDecoder::check(HTTPStreamDir& stream, HTTPStreamDir& otherDirection) {

	// currently: nothing to do
	if (stream.buffer.empty()) {return false;}

	// the stats object to work on for this stream's direction;
	HTTPDecoderStatsDir* curStats = (stream.isRequest) ? (&stats.requests) : (&stats.responses);



	// if the stream is waiting for a header, check if the buffer contains this header
	if (stream.state == HTTP_STREAM_WAITING_FOR_HEADER) {

		// check whether the buffer contains a header-end. if not -> skip
		int32_t pos = stream.buffer.indexOf( "\r\n\r\n" );
		if (pos == -1) {return false;}

		// sanity check
		if (pos < 14 || pos > 32*1024) {

			// all following traffic will be ignored (both directions!)
			stream.state = HTTP_STREAM_CORRUPTED;
			otherDirection.state = HTTP_STREAM_CORRUPTED;

			// log
			debug(DBG_HTTP, DBG_LVL_ERR, "strange header size. marking HTTP-stream as corrupted!");
			//stream.buffer.dump(std::cerr);

			return false;

		}


		debug(DBG_HTTP, DBG_LVL_INFO, "received header. length is: " << (pos + 4));

		// reset the stream to store the next header
		stream.reset();

		// get the header from the buffer.
		// this data will be removed from the header when this method ends and data is destructed
		DataBufferData data = stream.buffer.get(pos + 4);

		// create a string and a new header-object
		std::string header( (const char*) data.data, data.length );
		stream.header = new HTTPHeader();
		bool headerOK = stream.header->loadFromString(header);

		// if header-parsing failed (e.g. because of strange server behavior, skip everything
		// and mark BOTH directions as corrupted.
		if (!headerOK) {
			debug(DBG_HTTP, DBG_LVL_ERR, "header parsing failed. marking this connection as corrupted!");
			stream.state = HTTP_STREAM_CORRUPTED;
			otherDirection.state = HTTP_STREAM_CORRUPTED;
			return false;
		}

		// free the data
		data.free();

		// is this a request or a response?
		stream.isRequest = stream.header->isRequestHeader();

		// UPDATE the stats object as we now know this stream's direction;
		curStats = (stream.isRequest) ? (&stats.requests) : (&stats.responses);

		if (!stream.header->getURL().empty()) {
			debug(DBG_HTTP, DBG_LVL_DEBUG, "URL: " << stream.header->getURL());
		}

		// track average header sizes
		curStats->avgHeaderSize.add(stream.header->getLength());

		// cleanup any previous compression instances
		#ifdef WITH_ZLIB
			if (stream.unzip != nullptr) {delete stream.unzip; stream.unzip = nullptr;}
		#endif
		
		// is the next content compressed?
		if (stream.header->has("content-encoding", "gzip")) {
			#ifdef WITH_ZLIB
				++curStats->numCompressed;
				debug(DBG_HTTP, DBG_LVL_DEBUG, "gzip compression found");
				stream.unzip = new GZipDecompress();
			#else
				debug(DBG_HTTP, DBG_LVL_WARN, "found gzip compressed HTTP stream, but compiled without gzip support");
				stream.state = HTTP_STREAM_CORRUPTED;
				otherDirection.state = HTTP_STREAM_CORRUPTED;
				return false;
			#endif
		}


		// adjust stats
		++curStats->numHeaders;

		// inform listeners
		if (stream.isRequest) {
			for (auto it : listeners) {it->onHttpRequest(*this, *stream.header);}
		} else {

			// FIXME
			// after several hours the response header is set, but the request header isn't
			// and the app will crash with a nullptr.. thus we will use this sanity check here..
			if (otherDirection.header == nullptr) {
				debug(DBG_HTTP, DBG_LVL_ERR, "response-header available, but request-header isn't! marking this connection as corrupted!");
				stream.state = HTTP_STREAM_CORRUPTED;
				otherDirection.state = HTTP_STREAM_CORRUPTED;
				return false;
			}

			uint32_t latency = stream.header->getTimestamp() - otherDirection.header->getTimestamp();
			for (auto it : listeners) {it->onHttpResponse(*this, *otherDirection.header, *stream.header, latency);}

		}

		// check for latency information (if this is a response)
		//if (!stream.isRequest) {checkLatency();}


		// decide how to proceed
		if (stream.headerOnlyRequest) {
			stream.headerOnlyRequest = false;
			stream.state = HTTP_STREAM_WAITING_FOR_HEADER;
			debug(DBG_HTTP, DBG_LVL_INFO, "request was HEAD -> don't load any payload and proceed with next header");
			++curStats->numWithoutPayload;
			++curStats->numOK;

		} else if (stream.header->containsKey("content-length")) {
			stream.contentLength = strToInt(stream.header->get("content-length"));
			stream.state = HTTP_STREAM_WAITING_FOR_CONTENT;
			debug(DBG_HTTP, DBG_LVL_INFO, "normal content -> waiting for " << stream.contentLength << " bytes of payload");
			++curStats->numNormal;

		} else if (stream.header->has("transfer-encoding", "chunked")) {
			stream.state = HTTP_STREAM_WAITING_FOR_CHUNK_SIZE;
			debug(DBG_HTTP, DBG_LVL_INFO, "chunked content -> waiting for size-info of the next chunk");
			++curStats->numChunked;

		} else if (stream.header->has("connection", "close")) {
			stream.state = HTTP_STREAM_WAITING_FOR_UNKNOWN_CONTENT;
			debug(DBG_HTTP, DBG_LVL_INFO, "unknown content-length -> reading until connection closed");
			++curStats->numUnkownSize;

		} else {
			stream.state = HTTP_STREAM_WAITING_FOR_HEADER;
			debug(DBG_HTTP, DBG_LVL_INFO, "header without payload -> waiting for next header");
			++curStats->numWithoutPayload;
			++curStats->numOK;

		}

		// if only the HEAD(er) has been requested
		// the response-stream must not retrieve payload after the next header
		otherDirection.headerOnlyRequest = (stream.header->getMethod() == HTTP_METHOD_HEAD);

	}


	// receive "endless" content until connection: close
	if (stream.state == HTTP_STREAM_WAITING_FOR_UNKNOWN_CONTENT) {

		// skip when buffer is empty
		if (stream.buffer.empty()) {return false;}

		// get current buffer content
		DataBufferData data = stream.buffer.get();

		debug(DBG_HTTP, DBG_LVL_INFO, "buffer returned: " << data.length);

		// handle the incoming data
		handleData(stream, otherDirection, data);

		// increment receive-counter
		stream.contentReceived += data.length;

		// cleanup
		data.free();

	}

	// header received. is chunked. waiting for size-information of next chunk
	if (stream.state == HTTP_STREAM_WAITING_FOR_CHUNK_SIZE) {

		// we need at least 2 bytes to proceed
		if (stream.buffer.bytesUsed() < 2) {return false;}

		// wait for chunk-size info
		int pos = stream.buffer.indexOf("\r\n");
		if (pos == -1) {return false;}

		// read chunk-size from stream
		DataBufferData data = stream.buffer.get(pos+2);

		// store chunk-size
		std::string size( (const char*) data.data, data.length-2);
		stream.chunkLength = hexStringToInt(size);

		debug(DBG_HTTP, DBG_LVL_INFO, "next chunk's size is: " << stream.chunkLength);

		// remove from the buffer
		data.free();

		// now start loading chunk data
		stream.state = HTTP_STREAM_WAITING_FOR_CHUNK_DATA;
		debug(DBG_HTTP, DBG_LVL_INFO, "waiting for " << stream.chunkLength << " bytes of chunk-data");

	}

	// header received. content's size is known. waiting for content.
	if (stream.state == HTTP_STREAM_WAITING_FOR_CONTENT) {

		// get current buffer content
		// will be removed from buffer when this method returns
		uint32_t maxSize = stream.contentLength - stream.contentReceived;
		DataBufferData data = stream.buffer.get(maxSize);

		debug(DBG_HTTP, DBG_LVL_INFO, "content: " << maxSize << " bytes to go. buffer returned: " << data.length);

		// handle the incoming data
		handleData(stream, otherDirection, data);

		// increment receive-counter
		stream.contentReceived += data.length;

		// free the data
		data.free();

		// content completely received?
		if (stream.contentReceived == stream.contentLength) {

			stream.contentLength = 0;
			stream.contentReceived = 0;
			stream.state = HTTP_STREAM_WAITING_FOR_HEADER;
			debug(DBG_HTTP, DBG_LVL_INFO, "content complete");
			debug(DBG_HTTP, DBG_LVL_INFO, "waiting for next header");

			// inform listener
			for (auto it : listeners) {it->onHttpDone(*this, *stream.header);}

			// update stats
			++curStats->numOK;

		}

	} else if (stream.state == HTTP_STREAM_WAITING_FOR_CHUNK_DATA) {

		// get current buffer content
		// will be removed from buffer when this method returns
		uint32_t maxSize = stream.chunkLength - stream.contentReceived;
		DataBufferData data = stream.buffer.get(maxSize);

		debug(DBG_HTTP, DBG_LVL_INFO, "chunk: " << maxSize << " bytes to go. buffer returned: " << data.length);

		// handle the incoming data
		handleData(stream, otherDirection, data);

		// increment receive-counter
		stream.contentReceived += data.length;

		// free the data
		data.free();

		// chunk completely received?
		if (stream.contentReceived == stream.chunkLength) {
			stream.contentReceived = 0;
			stream.state = HTTP_STREAM_WAITING_FOR_CHUNK_END;
			debug(DBG_HTTP, DBG_LVL_INFO, "chunk complete");
			debug(DBG_HTTP, DBG_LVL_INFO, "waiting for chunk's trailing \\r\\n");

		}

	}

	// chunk received. waiting for the trailing "\r\n"
	if (stream.state == HTTP_STREAM_WAITING_FOR_CHUNK_END) {

		// each chunk ends with "\r\n"
		// wait for these two bytes here
		if (stream.buffer.bytesUsed() < 2) {return false;}
		DataBufferData data = stream.buffer.get(2);
		debug(DBG_HTTP, DBG_LVL_INFO, "received chunk's trailer");

		// immediately clean-up
		data.free();

		// if this was the last chunk (current chunkLength == 0)
		// we continue with a header, else we continue with another cunk
		if (stream.chunkLength == 0) {

			stream.state = HTTP_STREAM_WAITING_FOR_HEADER;
			debug(DBG_HTTP, DBG_LVL_INFO, "last chunk -> waiting for next header");

			// inform listeners
			for (auto it: listeners) {it->onHttpDone(*this, *stream.header);}

			// update stats
			++curStats->numOK;

		} else {
			stream.state = HTTP_STREAM_WAITING_FOR_CHUNK_SIZE;
			debug(DBG_HTTP, DBG_LVL_INFO, "waiting for another chunk's size");

		}

		// debug
		//stream.buffer.dump();
		stream.chunkLength = 0;
		stream.contentReceived = 0;

	}

	// corrupted? skip everything and wait for close()
	if (stream.state == HTTP_STREAM_CORRUPTED) {
		return false;
	}

	// everything fine. buffer might contain more usable data. return true -> try again
	return true;

}
void QWaveDecoder::handleData()
{
    // As a special "state", if we have junk to skip, we do
    if (junkToSkip > 0) {
        discardBytes(junkToSkip); // this also updates junkToSkip

        // If we couldn't skip all the junk, return
        if (junkToSkip > 0) {
            // We might have run out
            if (source->atEnd())
                parsingFailed();
            return;
        }
    }

    if (state == QWaveDecoder::InitialState) {
        if (source->bytesAvailable() < qint64(sizeof(RIFFHeader)))
            return;

        RIFFHeader riff;
        source->read(reinterpret_cast<char *>(&riff), sizeof(RIFFHeader));

        // RIFF = little endian RIFF, RIFX = big endian RIFF
        if (((qstrncmp(riff.descriptor.id, "RIFF", 4) != 0) && (qstrncmp(riff.descriptor.id, "RIFX", 4) != 0))
                || qstrncmp(riff.type, "WAVE", 4) != 0) {
            parsingFailed();
            return;
        } else {
            state = QWaveDecoder::WaitingForFormatState;
            if (qstrncmp(riff.descriptor.id, "RIFX", 4) == 0)
                bigEndian = true;
            else
                bigEndian = false;
        }
    }

    if (state == QWaveDecoder::WaitingForFormatState) {
        if (findChunk("fmt ")) {
            chunk descriptor;
            peekChunk(&descriptor);

            quint32 rawChunkSize = descriptor.size + sizeof(chunk);
            if (source->bytesAvailable() < qint64(rawChunkSize))
                return;

            WAVEHeader wave;
            source->read(reinterpret_cast<char *>(&wave), sizeof(WAVEHeader));

            if (rawChunkSize > sizeof(WAVEHeader))
                discardBytes(rawChunkSize - sizeof(WAVEHeader));

            // Swizzle this
            if (bigEndian) {
                wave.audioFormat = qFromBigEndian<quint16>(wave.audioFormat);
            } else {
                wave.audioFormat = qFromLittleEndian<quint16>(wave.audioFormat);
            }

            if (wave.audioFormat != 0 && wave.audioFormat != 1) {
                // 32bit wave files have format == 0xFFFE (WAVE_FORMAT_EXTENSIBLE).
                // but don't support them at the moment.
                parsingFailed();
                return;
            } else {
                format.setCodec(QLatin1String("audio/pcm"));

                if (bigEndian) {
                    int bps = qFromBigEndian<quint16>(wave.bitsPerSample);

                    format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
                    format.setByteOrder(QAudioFormat::BigEndian);
                    format.setSampleRate(qFromBigEndian<quint32>(wave.sampleRate));
                    format.setSampleSize(bps);
                    format.setChannelCount(qFromBigEndian<quint16>(wave.numChannels));
                } else {
                    int bps = qFromLittleEndian<quint16>(wave.bitsPerSample);

                    format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
                    format.setByteOrder(QAudioFormat::LittleEndian);
                    format.setSampleRate(qFromLittleEndian<quint32>(wave.sampleRate));
                    format.setSampleSize(bps);
                    format.setChannelCount(qFromLittleEndian<quint16>(wave.numChannels));
                }

                state = QWaveDecoder::WaitingForDataState;
            }
        }
    }

    if (state == QWaveDecoder::WaitingForDataState) {
        if (findChunk("data")) {
            source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));

            chunk descriptor;
            source->read(reinterpret_cast<char *>(&descriptor), sizeof(chunk));
            if (bigEndian)
                descriptor.size = qFromBigEndian<quint32>(descriptor.size);
            else
                descriptor.size = qFromLittleEndian<quint32>(descriptor.size);

            dataSize = descriptor.size;

            haveFormat = true;
            connect(source, SIGNAL(readyRead()), SIGNAL(readyRead()));
            emit formatKnown();

            return;
        }
    }

    // If we hit the end without finding data, it's a parsing error
    if (source->atEnd()) {
        parsingFailed();
    }
}
示例#24
0
文件: Selector.cpp 项目: yzoprj/trunk
void Selector::run()
{
	int result = 0;
	timeval tv = {3, 0};
	FD_SET readFds;
	FD_ZERO(&readFds);

	SessionManager *sm = SessionManager::getInstance();

	CommunicatioInformation tcpCi = _acceptor.getSocket().getCommunicationInformation();
	
	CommunicatioInformation udpCi = _udpAcceptor.getCommunicationInformation();
	
	_connectSessons.insert(make_pair(tcpCi.generateKeyForSocket(), _acceptor.getSocket()));
	
	_connectSessons.insert(make_pair(udpCi.generateKeyForSocket(), _udpAcceptor));

	map<string, SocketSession>::iterator iter  = _connectSessons.begin();
	
	isRunning = true;
	
	while (isRunning)
	{
		FD_ZERO(&readFds);

		
		
		iter  = _connectSessons.begin();
			
		while (iter != _connectSessons.end())
		{
			FD_SET(iter->second.getSession().getHandle(), &readFds);
			iter++;
		}

		result = select(0, &readFds, NULL, NULL, &tv);
		if (result == 0)
		{
			continue;
		}

		if (isRunning == false)
		{
			break;
		}


		if (FD_ISSET(_acceptor.getSocket().getHandle(), &readFds))
		{
			printDebugInfo("New Connection By TCP Service Accept");

			AsyncSocket session = _acceptor.acceptSession();
			
			CommunicatioInformation sCi = session.getCommunicationInformation();
			
			//iter = _connectSessons.find(sCi.generateKeyForSocket());
			//if (iter != _connectSessons.end())
			//{
			//	iter->second.getSession().close();
			//	printDebugInfo("Öظ´Á¬½Ó..........");
			//	_connectSessons.erase(iter);
			//}

			_connectSessons.insert(make_pair(sCi.generateKeyForSocket(), session));
			
			printDebugInfo("New Connection By TCP Server Accept");
			
		
		
		}else if (FD_ISSET(_udpAcceptor.getHandle(), &readFds))
		{
			printDebugInfo("New Message By UDP Server Accept");
			
			SocketSession ss(_udpAcceptor);
			
			handleData(ss);
		}
		else
		{
			iter = _connectSessons.begin();
			
			printDebugInfo("Client send message to the server in tcp mode");
			
			while (iter != _connectSessons.end())
			{
				SocketSession ss = iter->second;

				if (FD_ISSET(ss.session.getHandle(), &readFds))
				{
					handleData(ss);

				}
				iter++;
			}

			clearDisconnectionSession();

		}

		
	}

	clearSessions();
}
void QWaveDecoder::parsingFailed()
{
    Q_ASSERT(source);
    source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
    emit parsingError();
}
示例#26
0
Error XMLStreamDecoder::onWrite (const ByteArray & data) {
	mInputBuffer.append(data);
	handleData ();
	if (mState == XS_Error) return mError;
	return NoError;
}
示例#27
0
void TcpSocket::readData() {
    auto data  = handleData(this->readAll(),this->peerAddress().toString(),this->peerPort());
    qDebug() << data;
}
示例#28
0
void QWaveDecoder::handleData()
{
    if (state == QWaveDecoder::InitialState) {
        if (source->bytesAvailable() < qint64(sizeof(RIFFHeader)))
            return;

        RIFFHeader riff;
        source->read(reinterpret_cast<char *>(&riff), sizeof(RIFFHeader));

        if (qstrncmp(riff.descriptor.id, "RIFF", 4) != 0 ||
            qstrncmp(riff.type, "WAVE", 4) != 0) {
            source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
            emit invalidFormat();

            return;
        } else {
            state = QWaveDecoder::WaitingForFormatState;
        }
    }

    if (state == QWaveDecoder::WaitingForFormatState) {
        if (findChunk("fmt ")) {
            chunk descriptor;
            source->peek(reinterpret_cast<char *>(&descriptor), sizeof(chunk));

            if (source->bytesAvailable() < qint64(descriptor.size + sizeof(chunk)))
                return;

            WAVEHeader wave;
            source->read(reinterpret_cast<char *>(&wave), sizeof(WAVEHeader));
            if (descriptor.size > sizeof(WAVEHeader))
                discardBytes(descriptor.size - sizeof(WAVEHeader));

            if (wave.audioFormat != 0 && wave.audioFormat != 1) {
                source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
                emit invalidFormat();

                return;
            } else {
                int bps = qFromLittleEndian<quint16>(wave.bitsPerSample);

                format.setCodec(QLatin1String("audio/pcm"));
                format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
                format.setByteOrder(QAudioFormat::LittleEndian);
                format.setFrequency(qFromLittleEndian<quint32>(wave.sampleRate));
                format.setSampleSize(bps);
                format.setChannels(qFromLittleEndian<quint16>(wave.numChannels));

                state = QWaveDecoder::WaitingForDataState;
            }
        }
    }

    if (state == QWaveDecoder::WaitingForDataState) {
        if (findChunk("data")) {
            source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));

            chunk descriptor;
            source->read(reinterpret_cast<char *>(&descriptor), sizeof(chunk));
            dataSize = descriptor.size;

            haveFormat = true;
            connect(source, SIGNAL(readyRead()), SIGNAL(readyRead()));
            emit formatKnown();

            return;
        }
    }

    if (source->atEnd()) {
        source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));
        emit invalidFormat();

        return;
    }

}