1
我在Qt上編寫客戶/服務器通信系統。我正在使用QTcpServer和QtcpSocket。我從客戶端發送一些信息,但是如何從服務器返回值?QTcpServer:如何返回值?
客戶端
QTcpSocket *socket = new QTcpSocket(this);
socket->connectToHost("MyHost", "MyPort");
socket->write("Hello from Client...");
服務器端
QtSimpleServer::QtSimpleServer(QObject *parent) : QTcpServer(parent)
{
if (listen(QHostAddress::Any, "MyPort"))
{
qDebug() << "Listening...";
}
else
{
qDebug() << "Error while listening... " << errorString();
}
}
void QtSimpleServer::incomingConnection(int handle)
{
QTcpSocket *socket = new QTcpSocket();
socket->setSocketDescriptor(handle);
connect (socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}
void QtSimpleServer::onReadyRead()
{
QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
qDebug() << socket->readAll();
socket->disconnectFromHost();
socket->close();
socket->deleteLater();
}
你可以使用'插座 - > write'方法。順便說一句,你應該注意到,數據包可能會被分割,並且不保證你會用全部的'readAll()'來尊重所有的數據。 –
如何從服務器返回值?什麼價值?您可能需要將客戶端指針保存爲 – saeed
@saeed例如:我想發送給客戶端「來自服務器的Hello」。我該怎麼做? –