/ / Qt:QTcpSocketを使う - >ソケットに書くことはできるが、読むことができない… - c ++、qt、sockets、tcp

Qt:QTcpSocketを使用する - >私はソケットで書くことができますが、私は読むことができません... - c ++、qt、ソケット、tcp

xUbuntu 14.04でQt 4.8 GCC 32bitを使用しています。
私は次のようなコードを持っています。これは、リモートコマンドを受け取って答えを返すために使用するTCPサーバーです。TCPソケット経由で。

struct _MyRequest
{
unsigned long   Request;
unsigned long   Data;
} __attribute__((packed));

struct _MyAnswer
{
unsigned long   Error;
unsigned long   Filler;
} __attribute__((packed));

_MyRequest request;
_MyAnswer  answer;

RemoteCmdServer::RemoteCmdServer(QObject * parent)
: QTcpServer(parent)
{
qDebug() << "Server started";

listen(QHostAddress("172.31.250.110"), 5004);

connect(this, SIGNAL(newConnection()), this, SLOT(processPendingRequest()));
}

void RemoteCmdServer::processPendingRequest()
{
qDebug() << "Process request";

QTcpSocket * clientConnection = nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

// get the request
int ret = clientConnection->read((char*)&request, sizeof(request));
qDebug() << "READ: " << ret;
if(ret == sizeof(request))
{
// send answer
clientConnection->write((char*)&answer, sizeof(answer));
}

qDebug() << "Disconnecting...";
clientConnection->disconnectFromHost();
}

コメントすれば正しく書くことができます if(ret == sizeof(request)) ライン。
それでも、ソケットから読み取ることはできません(常に0バイトになります)。
私は自分のアプリにパケットを送信するために使用するTCPツールが問題なく動作することを100%確信しています。
これが私のアプリからのデバッグ出力です。

Server started
Process request
READ: 0
Disconnecting...

何がおかしいのですか?お知らせ下さい!

回答:

回答№1は1

あなたは、ノンブロッキングまたはブロッキング方法でデータを待つべきです。あなたが使用することができます waitForReadyRead ブロッキング方法でそれをするために。

void RemoteCmdServer::processPendingRequest()
{
qDebug() << "Process request";

QTcpSocket * clientConnection = nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

if (clientConnection->waitForReadyRead())
{
// get the request
QByteArray message = clientConnection->readAll(); // Read message
qDebug() << "Message:" << QString(message);
}
else
{
qDebug().nospace() << "ERROR: could not receive message (" << qPrintable(clientConnection->errorString()) << ")";
}

qDebug() << "Disconnecting...";
clientConnection->disconnectFromHost();
}

回答№2の場合は1

あなたは「Qtイベントループに戻らずに新しい接続からデータを読み込もうとしています - うまくいくとは思わない」

あなたが「接続を受け入れた後」

QTcpSocket * clientConnection = nextPendingConnection();

あなたはそれに接続する必要があります readyRead のようなもので信号を送る...

connect(clientConnection, SIGNAL(readyRead()), this, SLOT(my_read_slot()));

どこで my_read_slot 実際に読み取り操作を実行するメンバー関数です。