Esempio n. 1
0
void JNetwork::ThreadProc(void* param)
{
    JNetwork* pThis = reinterpret_cast<JNetwork*>(param);
    JSocket* pSocket = NULL;
    if (pThis->serverIP.size()) {
        DebugTrace("Starting Client Thread");
        pThis->socket = new JSocket(pThis->serverIP);
        if(pThis->socket->isConnected())
            pSocket = pThis->socket;
    } else {
        DebugTrace("Starting Server Thread");
        pThis->socket = new JSocket();
        // Wait for some client
        pSocket = pThis->socket->Accept();
    }

    while(pSocket && pSocket->isConnected()) {
        char buff[4096];
        {
            int len =  pSocket->Read(buff, sizeof(buff));
            if(len > 0) {
                boost::mutex::scoped_lock l(pThis->receiveMutex);
                DebugTrace("receiving " << len << " bytes : " << buff);
                pThis->received.str(pThis->received.str() + buff);
                DebugTrace("received " << pThis->received.str().size() << " bytes : " << pThis->received.str());
            }
        }
        {
            boost::mutex::scoped_lock l(pThis->sendMutex);
            if(!pThis->toSend.str().empty())
            {
                DebugTrace("sending  " << pThis->toSend.str().size() << " bytes : " << pThis->toSend.str());
                pSocket->Write((char*)pThis->toSend.str().c_str(), pThis->toSend.str().size()+1);
                pThis->toSend.str("");
            }
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(1));
    }

    DebugTrace("Quitting Thread");
}