2017-09-27 48 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

에 모습을 가지고하는 것이 좋습니다. Btw, 당신은주의해야한다, 그 패킷은 단편화 될 것이고, 모든 데이터를'readAll()'으로 모두 보게 될 것이라는 보장은 없다. –

+0

서버에서 어떻게 값을 반환 할 수 있습니까? 어떤 가치? – saeed

+0

@saeed 예를 들어 클라이언트 "Hello from server"로 보내려고합니다. 내가 어떻게 해? –

답변

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(); 
    } 
} 

참고

이 범위 안에 만들어지고 나중에 참조되어야 개체 참조 저장 표시하기 만하는 간단한 해결책이다.

더 복잡한 서버/클라이언트 응용 프로그램을 실행하려면

는, 당신이 방법 write``소켓 ->를 사용할 수 Threaded Fortune Server ExampleFortune Client Example