2017-09-27 73 views
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(); 
} 
+1

你可以使用'插座 - > write'方法。順便說一句,你應該注意到,數據包可能會被分割,並且不保證你會用全部的'readAll()'來尊重所有的數據。 –

+0

如何從服務器返回值?什麼價值?您可能需要將客戶端指針保存爲 – saeed

+0

@saeed例如:我想發送給客戶端「來自服務器的Hello」。我該怎麼做? –

回答

2

另存爲進一步響應每個客戶的指針。

QVector<QTcpSocket*> clients; 
void QtSimpleServer::incomingConnection(qintptr handle) 
{ 
    QTcpSocket *socket = new QTcpSocket(); 
    socket->setSocketDescriptor(handle); 
    connect (socket, SIGNAL(readyRead()), this, SLOT(onReadyRead())); 
    clients << socket; 
} 

void QtSimpleServer::sendHelloToAllClient() 
{ 
    foreach (QTcpSocket * client, clients) { 
     client->write(QString("Hello Client").toLatin1()); 
     client->flush(); 
    } 
} 

注:

這只是一個簡單的解決方案,以顯示節省這是一個範圍內創建,應以後引用對象的引用。

如果你想練習更復雜的服務器/客戶端應用程序

,最好是有旁觀Threaded Fortune Server ExampleFortune Client Example