如何将Android应用程序(java)连接到Tcp服务器(Qt,C ++)

时间:2016-03-18 16:15:40

标签: java android c++ qt

我有一个Tcp Server是用C ++编写的,Qt和我需要的是我的应用程序在android上可以连接到服务器发送和读取接收的数据,但我无法理解如何实现它。我试过用Qt Jambi但事实证明这个库不支持android应用程序开发,我也尝试在我的Android应用程序Qt库中使用,其中有连接到服务器的方法,读取和发送,但是套接字未连接到服务器。

  

Server.h

class Server : public QTcpServer
{
    Q_OBJECT
public:
    Server(QObject *parent = 0);
    ~Server();
    void startServer();
protected:
    void incomingConnection( qintptr handle );
private:
    QThreadPool *pool;
};
  

Server.cpp

Server::Server(QObject *parent) :
    QTcpServer(parent)
{
    pool = new QThreadPool(this);
    pool->setMaxThreadCount(5);
}

Server::~Server()
{
    delete pool;
}

void Server::startServer()
{
    if(listen(QHostAddress::Any, 8080)){
        qDebug() << "Server started";
    }else{
        qDebug() << "Server did not start!";
    }
}

void Server::incomingConnection(qintptr handle)
{
    Runnable *runnable = new Runnable();
    runnable->setAutoDelete(true);
    connect(runnable->dataBase, SIGNAL(sendMessageToEmail(QStringList)), this, SLOT(sendMail(QStringList)));
    runnable->socketDescriptor = handle;

    pool->start(runnable);
}
  

Runnable.cpp

    ...
    void Runnable::run()
    {
        if(!socketDescriptor){
            return;
        }

        socket = new QTcpSocket;
        socket->setSocketDescriptor(socketDescriptor);
        QObject::connect(&(*socket), SIGNAL(disconnected()), this, SLOT(disconected()));
        outStream << quint16(0);

        while(socket->isOpen())
        {
            socket->waitForReadyRead();
            if(socket->bytesAvailable() == 0){
                continue;
            }
            onReadyRead();
        }
    }

void Runnable::sendToUser()
{
    outStream.device()->seek(0);
    outStream << quint16(arrByteOut.size() - sizeof(quint16));
    socket->write(arrByteOut);
    socket->waitForBytesWritten();
}

void Runnable::onReadyRead()
{
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_5_5);

    if(socket->isOpen())
    {
        if(nextBlockSize == 0){
            in >> nextBlockSize;
        }

        if(socket->bytesAvailable() < nextBlockSize){
            return;
        }

        if(socket->isOpen()){
            queryDefinition(in);
            nextBlockSize = 0;
        }
    }
}
    ...

提前致谢。

0 个答案:

没有答案