Esempio n. 1
0
	dword ClientTask()
	{
		CScopedLock _lock;
		CTcpClient* pClient = NULL;
		CDataDoubleLinkedListT<CTcpClient>::Iterator it = _tcpclients.Begin();
				
		if ( it && (*it) )
		{
			pClient = *it;
			_tcpclients.Remove(it, EmptyDeleteFunc, NULL);
		}
		if ( !pClient )
			return 0;

		CStringBuffer sBuffer;

		wcout(_T("ClientTask"));
		try
		{
			CStringConstIterator itB;
			bool bExit = false;

			_lock.unlock();
			ReceiveData(pClient, sBuffer);
			wcout(sBuffer.GetString());
			SendData(pClient, sBuffer);

			ReceiveData(pClient, sBuffer);
			wcout(sBuffer.GetString());
			SendData(pClient, sBuffer);

			ReceiveData(pClient, sBuffer);
			wcout(sBuffer.GetString());
			SendData(pClient, sBuffer);

			ReceiveData(pClient, sBuffer);
			wcout(sBuffer.GetString());
			SendData(pClient, sBuffer);

			ReceiveData(pClient, sBuffer);
			itB = sBuffer;
			itB.Find(_T("STOP\r\n"));
			if ( itB.IsBegin() )
				bExit = true;
			wcout(sBuffer.GetString());
			SendData(pClient, sBuffer);

			pClient->CloseConnection();
			_lock.lock();
			pClient->release();
			_bExit = bExit;
		}
		catch ( CTcpClientException* ex )
		{
			COUT << ex->GetExceptionMessage() << endl;
			pClient->CloseConnection();
		}
		return 0;
	}
Esempio n. 2
0
static int Send_Command(unsigned char *DataBuffer, unsigned int Size)
{
    int Temp;

    Temp = -1;
    while(Temp == -1)
    {
        Temp = Send_Packet(DataBuffer, Size);
    }

    Temp = -1;
    while(Temp == -1)
    {
        Temp = Send_Packet(command_get_status, 1);
    }

    //Temp = 0;
    ReceiveData((unsigned char *)&Temp, 1);

    if(Temp != COMMAND_RET_SUCCESS)
    {
        return -1;
    }

    // This command is executed successfully
    return 0;
}
Esempio n. 3
0
void CSocketEngine::GetData(){
  if(iCount==1){//如果是接收文件的第一个数据包
    if(!GetFirstData()) return;
  }
  if(0==iSpeed){//网速未知
    if(2==iCount){
      iTimeTestSpeed1.HomeTime();
      iSizeTestSpeed1=iData1.Length();
      iSizeTestSpeed2=iSizeTestSpeed1;
    }
    if(iCount>2){
      iSizeTestSpeed2+=iData1.Length();
      if((iSizeTestSpeed2-iSizeTestSpeed1)>iTestSpeedSize){
        iTimeTestSpeed2.HomeTime();
        TTimeIntervalSeconds seconds(0);
        TInt err=iTimeTestSpeed2.SecondsFrom(iTimeTestSpeed1,seconds);
        if(!err){
          TInt sec=seconds.Int();
          iSpeed=(sec>0)?((iSizeTestSpeed2-iSizeTestSpeed1)/sec):KMaxNetSpeed;
          OnHttpSktEvent(EHttpSktEvtSpeedKnown);
        }
      }
    }
  }
  if(bSearch){
    if(iCount==1){
      iData->Des().Zero();
      iReceivedLen=0;
    }
    TBool needSaveFile=this->iDownloadFilePath.Length()>0;
    if(!needSaveFile){
      TInt n=iData->Des().Length()+iData1.Length();
      TInt m=iData->Des().MaxLength();
      if(n<m) iData->Des().Append(iData1);
    }
    iReceivedLen+=iData1.Length();
    if((iReceivedLen-iHttpHeadOverPos)<iTotalLen){
      if(needSaveFile) this->SaveToFile(iData1);
      ReceiveData();
    }else{
      if(iTimer->IsActive()) iTimer->Cancel();
      if(needSaveFile){
        this->SaveToFile(iData1);
        if(iObserver) iObserver->OnDownloadFinished(this->iDownloadFilePath);
      }else if(iObserver){
        int iLen=iData->Length()-iHttpHeadOverPos;
        if(iLen<=0){
          iObserver->OnResponseReceived(_L8(""));
        }else{
          iObserver->OnResponseReceived(iData->Mid(iHttpHeadOverPos,iLen));
        }
      }
      iDownloading=EFalse;
      Cancel();
      iSocket.Close();
    }
  }else{
    if(iObserver) iObserver->OnResponseReceived(iData1);
  }
}
Esempio n. 4
0
int iNet::TcpSocket::Impl::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QTcpSocket::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: SendDataSignal((*reinterpret_cast< QByteArray(*)>(_a[1]))); break;
        case 1: ConnectToHostSignal((*reinterpret_cast< Utils::HostInf(*)>(_a[1]))); break;
        case 2: DisconnectFromHostSignal(); break;
        case 3: DeleteSignal((*reinterpret_cast< boost::shared_ptr<Utils::ThreadSyncEvent>(*)>(_a[1]))); break;
        case 4: ConnectToHostSlot((*reinterpret_cast< const Utils::HostInf(*)>(_a[1]))); break;
        case 5: ConnectedSlot(); break;
        case 6: SendDataSlot((*reinterpret_cast< const QByteArray(*)>(_a[1]))); break;
        case 7: ReceiveData(); break;
        case 8: DisconnectFromHostSlot(); break;
        case 9: DisconnectedSlot(); break;
        case 10: SocketErrorOccur((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
        case 11: DeleteSlot((*reinterpret_cast< boost::shared_ptr<Utils::ThreadSyncEvent>(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 12;
    }
    return _id;
}
Esempio n. 5
0
/**
  Process asynchronous requests.
*/
TInt DZeroCopyLoopbackChannel::DoRequest(TInt aReqNo, TRequestStatus* aStatus, TAny* a1, TAny* a2)
	{
	(void)a2;   // a2 not used in this example

	TInt r;

	switch(aReqNo)
		{
		case RZeroCopyLoopbackDriver::ESendData_ByZeroCopy:
			r = SendData(aStatus, (TInt)a1);
			break;

		case RZeroCopyLoopbackDriver::EReceiveData_ByZeroCopy:
			// Example Platform Security capability check which tests the
			// client for ECapability_None (which always passes)...
			if(iClient->HasCapability(ECapability_None,__PLATSEC_DIAGNOSTIC_STRING("Checked by zerocopy loopback")))
				r = ReceiveData(aStatus, (TInt*)a1);
			else
				r = KErrPermissionDenied;
			break;

		default:
			r = KErrNotSupported;
			break;
		}

	return r;
	}
Esempio n. 6
0
BOOL ClientEngine::Render()
{
	if(m_ConnectState == Not_Connect)
	{
		return FALSE;
	}

	if(m_ConnectState == Start_Connect)
	{
		return FALSE;
	}

	if(m_ConnectState == Raw_Connect)
	{

	}

	if(ReceiveData())
	{
		ProcessData();
	}

	return TRUE;

}
Esempio n. 7
0
static void
setup_ipc(void)
{
   int k, port = 10001;

   if (MyID == 0) {
      /* I'm the first one, wait for connection from second */
      k = CreatePort(&port);
      assert(k != -1);

      printf("Waiting for connection from another 'corender'\n");
      Sock = AcceptConnection(k);
      assert(Sock != -1);

      printf("Got connection, sending windowID\n");

      /* send windowID */
      SendData(Sock, &WindowID, sizeof(WindowID));
   }
   else {
      /* I'm the second one, connect to first */
      char hostname[1000];

      MyHostName(hostname, 1000);
      Sock = Connect(hostname, port);
      assert(Sock != -1);

      /* get windowID */
      ReceiveData(Sock, &WindowID, sizeof(WindowID));
      printf("Contacted first 'corender', getting WindowID\n");
   }
}
Esempio n. 8
0
void LeyboldGraphixThree::SetDisplayUnit(LeyboldGraphixThree::DisplayUnit unit)
{
  std::string name;

  std::map<DisplayUnit,std::string>::const_iterator itFind = displayUnitNames_.find(unit);
  if (itFind!=displayUnitNames_.end()) {
    name = itFind->second;
  } else {
    return;
  }

  std::string command;

  command += SO;
  command += "5";
  command += Separator;
  command += "4";
  command += Separator;
  command += name;

  SendCommand(command);

  std::string buffer;
  bool isACK = ReceiveData(buffer);
}
Esempio n. 9
0
/*
 * Manual page at process.def
 */
INT16 CGEN_PUBLIC CProcess::Wait()
{
  const SMic* pMic    = NULL;                                                   // Method invocation context of Wait()
  CFunction*  iCaller = NULL;                                                   // Function instance calling Wait()

  // Validate and initialize                                                    // ------------------------------------
  if (!((m_nState & PRC_RUNNING)|PRC_COMPLETE))                                 // Not running
    return IERROR(this,PRC_CANTWAIT,"not started",0,0);                         //   Forget it
  if (!(pMic = CDlpObject_MicGet(_this))) return -1;                            // Get method invocation context
  iCaller = (CFunction*)CDlpObject_OfKind("function",pMic->iCaller);            // Get calling CFunction
  if (!iCaller) return -1;                                                      // Must be a function!

  // Wait for job to be completed                                               // ------------------------------------
#ifdef USE_FORK
  if(!m_hThread && m_hPid){                                                     // If there is a child process by fork >>
    waitpid(m_hPid,NULL,0);                                                     //   Wait for child process
    m_nState &= ~PRC_RUNNING;                                                   //   Clear running flag
    m_nState |= PRC_COMPLETE;                                                   //   Set completed flag
  }else                                                                         // <<
#endif
  dlp_join_thread(m_hThread);                                                   // Wait for the watcher thread to end
  ReceiveData();                                                                // Receive transfer data

  // Aftermath                                                                  // ------------------------------------
  if (m_iDto)                                                                   // This job was a function call
    Unmarshal(m_iDto,iCaller);                                                  //   Unmarshal transfer data to caller
  else                                                                          // This job was a program call
    MIC_PUT_N(m_nRetVal);                                                       //   Push process return value

  return O_K;                                                                   // Ok
}
Esempio n. 10
0
void LeyboldGraphixThree::SetSetPointChannelAssignment(int sp, VLeyboldGraphixThree::SetPointChannel channel)
{
  if (sp<1 || sp>6) return;

  std::string command;

  command += SO;
  command += "4";
  command += Separator;
  command += std::to_string((sp-1)*4 + 1);
  command += Separator;

  if (channel==SetPointChannel1) {
    command += "1";
  } else if (channel==SetPointChannel2) {
    command += "2";
  } else if(channel==SetPointChannel3) {
    command += "3";
  } else {
    command += "Off";
  }

  SendCommand(command);

  std::string buffer;
  bool isACK = ReceiveData(buffer);
}
Esempio n. 11
0
VLeyboldGraphixThree::SetPointChannel LeyboldGraphixThree::GetSetPointChannelAssignment(int sp) const
{
  if (sp<1 || sp>6) return SetPointChannelOff;

  std::string command;

  command += SI;
  command += "4";
  command += Separator;
  command += std::to_string((sp-1)*4 + 1);

  SendCommand(command);

  std::string buffer;
  bool isACK = ReceiveData(buffer);

  if (buffer=="Off") {
    return SetPointChannelOff;
  } else if (buffer=="1") {
    return SetPointChannel1;
  } else if (buffer=="2") {
    return SetPointChannel2;
  } else if (buffer=="3") {
    return SetPointChannel3;
  }

  return SetPointChannelOff;
}
Esempio n. 12
0
static int Send_Packet(unsigned char * DataBuffer, unsigned int Size)
{
    unsigned int Temp;

    //caculated the checksum to be sent out with the data
    Temp = CheckSum(DataBuffer, Size);
    
    //Need to include the size (1 byte) and checksum (1 byte) in the packet
    Size += 2;

    // Send out the size , checkres followed by the Data

    SendData((unsigned char *)&Size, 1);
    SendData((unsigned char *)&Temp, 1);
    SendData(DataBuffer, Size - 2);

    //wait for a non-zero byte 
    Temp = 0;
    while(Temp == 0)
    {
        ReceiveData((unsigned char *)&Temp, 1);
    }

    // Check if the byte was a valid ACK and Return -1 if it is not ACK

    if(Temp != COMMAND_ACK)
    {
        return -1;
    }

    //This packet is sent out and received successfully by the M4 bootloader
    return 0;

}
Esempio n. 13
0
/**
 * This function performes handshake procedure
 */
static jdwpTransportError 
CheckHandshaking(jdwpTransportEnv* env, SOCKET sckt, jlong handshakeTimeout)
{
    const char* handshakeString = "JDWP-Handshake";
    char receivedString[14]; //length of "JDWP-Handshake"

    jlong deadline = (handshakeTimeout == 0) ? 0 : (jlong)GetTickCount() + handshakeTimeout;

    jdwpTransportError err;
    err = SendData(env, sckt, handshakeString, (int)strlen(handshakeString), deadline);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        SetLastTranErrorMessagePrefix(env, "'JDWP-Handshake' sending error: ");
        return err;
    }

    err = ReceiveData(env, sckt, receivedString, (int)strlen(handshakeString), deadline);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        SetLastTranErrorMessagePrefix(env, "'JDWP-Handshake' receiving error: ");
        return err;
    }

    if (memcmp(receivedString, handshakeString, 14) != 0) {
        SetLastTranError(env, "handshake error, 'JDWP-Handshake' is not received", 0);
        return JDWPTRANSPORT_ERROR_IO_ERROR;
    }

    return JDWPTRANSPORT_ERROR_NONE;
}// CheckHandshaking
Esempio n. 14
0
int32_t ReceiveMsg(int socket, char **buffer){
    int32_t data_size=0;
    //Read incoming data size
    if(ReceiveData(socket,(void *)&data_size,sizeof(data_size))==-1){
        close(socket);
        return -1;
    }    
    data_size=ntohl(data_size);
    *buffer=new char[data_size];

    if(ReceiveData(socket,(void *)(*buffer),data_size)==-1){
        close(socket);
        return -1;
    }
    
    return data_size;
}
Esempio n. 15
0
HttpHandler::HttpHandler(QTcpSocket * s, bool api, bool violetapi):pluginManager(PluginManager::Instance())
{
	incomingHttpSocket = s;
	httpApi = api;
	httpVioletApi = violetapi;
	bytesToReceive = 0;
	connect(s, SIGNAL(readyRead()), this, SLOT(ReceiveData()));
}
Esempio n. 16
0
uint8_t i2c_t::CmdWriteRead(uint8_t Addr,
        uint8_t *WPtr, uint8_t WLength,
        uint8_t *RPtr, uint8_t RLength) {
    if(IBusyWait() != OK) return FAILURE;
    // Clear flags
    ii2c->SR1 = 0;
    while(RxIsNotEmpty()) (void)ii2c->DR;   // Read DR until it empty
    ClearAddrFlag();
    // Start transmission
    SendStart();
    if(WaitEv5() != OK) return FAILURE;
    SendAddrWithWrite(Addr);
    if(WaitEv6() != OK) { SendStop(); return FAILURE; }
    // Start TX DMA if needed
    if(WLength != 0) {
        if(WaitEv8() != OK) return FAILURE;
        dmaStreamSetMemory0(PDmaTx, WPtr);
        dmaStreamSetTransactionSize(PDmaTx, WLength);
        PRequestingThread = chThdSelf();
        dmaStreamEnable(PDmaTx);
        chSysLock();
        chSchGoSleepS(THD_STATE_SUSPENDED); // Sleep until end
        chSysUnlock();
        dmaStreamDisable(PDmaTx);
    }
    // Read if needed
    if(RLength != 0) {
        if(WaitEv8() != OK) return FAILURE;
        // Send repeated start
        SendStart();
        if(WaitEv5() != OK) return FAILURE;
        SendAddrWithRead(Addr);
        if(WaitEv6() != OK) { SendStop(); return FAILURE; }
        // If number of data to be read is 1, then DMA cannot be used
        if(RLength == 1) {
            AckDisable();
            SendStop();
            if(WaitRx() != OK) return FAILURE;
            *RPtr = ReceiveData();
            if(WaitStop() != OK) return FAILURE;
            return OK;
        }
        else {  // more than 1 byte, use DMA
            AckEnable();
            dmaStreamSetMemory0(PDmaRx, RPtr);
            dmaStreamSetTransactionSize(PDmaRx, RLength);
            DmaLastTransferSet(); // Inform DMA that this is last transfer => do not ACK last byte
            PRequestingThread = chThdSelf();
            dmaStreamEnable(PDmaRx);
            chSysLock();
            chSchGoSleepS(THD_STATE_SUSPENDED); // Sleep until end
            chSysUnlock();
            dmaStreamDisable(PDmaRx);
        } // if lng==1
    } // if != 0
    SendStop();
    return OK;
}
Esempio n. 17
0
String MultiReceiver::ReceiveMulti()
{
	pinMode(_pinId, INPUT);

	ResetVariables();
	WaitForLongLow();
	RearrangeReadings();
	return ReceiveData();
}
Esempio n. 18
0
/**
  DMA complete notification handler function. This function will be called
  by the PDD from the DMA Rx service function on successful DMA Rx operation.
  It notifies the user about receive request completion.
  
  @param	aSize
  			Accumulated size of data received over all individual reads.
  			aResult
  			DMA operation return value.
*/
 void DExDriverLogicalChannel::RxDmaComplete(TInt aSize, TInt aResult)
 	{
 	
 	KEXDEBUG(Kern::Printf("++DExDriverLogicalChannel::RxDmaComplete")); 	
 	
 	
	// Action required only if a Rx request is issued and is pending
	//
	if (iRxDataStatus)	
		{
		// If this function is called on error condition, fail the user request
		if (aResult==KErrGeneral)
			{
			// Complete the current request with the abort result.
			Kern::RequestComplete(iClient,iRxDataStatus,aResult);
			return;
			}
						
		// aSize will have the number of bytes recieved in the transfer.
	 	iBytesRxed = iBytesRxed-aSize;
	 	
	 	// Calculate the offset till where the data is written.
		iRxOffset+=aSize;
		
		if (iBytesRxed<=0)
				{
				Kern::RequestComplete(iClient,iRxDataStatus,KErrNone);	
				return;
				}
				
		// If the DFC is scheduled on a Rx timeout condition, then
		// complete the request with timeout result
		//
		if (aResult==KErrTimedOut)
			{	
			
				// Complete the current request with the timeout result.
				Kern::RequestComplete(iClient,iRxDataStatus,aResult);
			return;
			}
	 	
	 	
	 	// If we have reached the end of the chunk.
	 	// then wrap around to the initial offset position. (User specified Offset)
	 	if (iRxOffset == Pdd()->iRxChunk->iSize)		
	 		{
	 		iRxOffset =  iRxInitialOffset;
	 		}
		
		// Re-start receiving the data
		ReceiveData(iRxOffset,iBytesRxed);
		
		
		return;		
		}
 	}
Esempio n. 19
0
void CReceiverThread::Initialize( )
{
    QString strParkID = pWinPort->objectName( );
    strParkID = pConfig->GetComParkID( strParkID );
    pParserThread = CParserThread::CreateThread( strParkID );
    connect( pWinPort, SIGNAL( readyRead( ) ),
             this, SLOT( ReceiveData( ) ) );
    connect( pParserThread, SIGNAL( Log( QString, bool ) ),
             this, SLOT( HandleLog( QString, bool ) ) );
}
Esempio n. 20
0
void CNetRender::ReceiveFromClient()
{
	// get client by signal emitter
	QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
	int index = GetClientIndexFromSocket(socket);
	if(index != -1)
	{
		ReceiveData(socket, &clients[index].msg);
	}
}
Esempio n. 21
0
void BufferIOEvent::OnEvents(uint32_t events) {
  /// The WRITE events should deal with before the READ events
  if (events & IOEvent::WRITE) {
    SendData();
  }
  if (events & IOEvent::READ) {
    ReceiveData();
  }
  if (events & IOEvent::ERROR) {
    OnError(errno, strerror(errno));
  }
}
Esempio n. 22
0
static void UserFunc_1(void)
{
    /*network*/
        
    ReceiveData();
    SendData(); 
    
    #ifdef DEBUG_PC
    //inData.readStatus = READ_OK;
    #endif
 
}
void
BluetoothDaemonConnectionIO::OnSocketCanReceiveWithoutBlocking()
{
  ssize_t res = ReceiveData(GetFd());
  if (res < 0) {
    /* I/O error */
    RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
  } else if (!res) {
    /* EOF or peer shutdown */
    RemoveWatchers(READ_WATCHER);
  }
}
Esempio n. 24
0
void
UnixSocketConsumerIO::OnSocketCanReceiveWithoutBlocking()
{
  MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
  MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); // see bug 990984

  nsresult rv = ReceiveData(GetFd(), this);
  if (NS_FAILED(rv)) {
    RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
    return;
  }
}
Esempio n. 25
0
string TCP::ReceiveDataExclamation()
{
	string temp = "";
	while (true)
	{
		temp += ReceiveData();
		if (FindExclamation(temp))
		{
			break;
		}
	}
	return temp;
}
void
ConnectionOrientedSocketIO::OnSocketCanReceiveWithoutBlocking()
{
  MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
  MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); // see bug 990984

  ssize_t res = ReceiveData(GetFd());
  if (res < 0) {
    /* I/O error */
    RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
  } else if (!res) {
    /* EOF or peer shutdown */
    RemoveWatchers(READ_WATCHER);
  }
}
Esempio n. 27
0
BOOL ReceiveString(HANDLE hPipe, TCHAR** lpStr)
{
    DWORD read;
    TCHAR* str;
    BOOL result = ReceiveData(hPipe, (LPVOID*)&str, &read);

    if (result && *(str + (read / sizeof(TCHAR)) - 1) != 0) {
        SetLastError(ERROR_PIPE_NOT_NULL_TERMINATED_STRING);
        MemoryFree(str);
        return FALSE;
    }

    *lpStr = str;
    return result;
}
Esempio n. 28
0
std::string LeyboldGraphixThree::GetItemNumber() const
{
  std::string command;

  command += SI;
  command += "5";
  command += Separator;
  command += "3";

  SendCommand(command);

  std::string buffer;
  bool isACK = ReceiveData(buffer);

  return buffer;
}
Esempio n. 29
0
int LeyboldGraphixThree::GetNumberOfChannels() const
{
  std::string command;

  command += SI;
  command += "5";
  command += Separator;
  command += "8";

  SendCommand(command);

  std::string buffer;
  bool isACK = ReceiveData(buffer);

  return std::atoi(buffer.c_str());
}
void
BluetoothDaemonConnectionIO::OnSocketCanReceiveWithoutBlocking()
{
  MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
  MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED);
  MOZ_ASSERT(!IsShutdownOnIOThread());

  ssize_t res = ReceiveData(GetFd());
  if (res < 0) {
    /* I/O error */
    RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
  } else if (!res) {
    /* EOF or peer shutdown */
    RemoveWatchers(READ_WATCHER);
  }
}