我正在Qt上编写客户机/服务器通信系统。我正在使用QTcpServer和QtcpSocket。我正在从客户端发送一些信息,但是如何从服务器返回值呢?
客户端
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();
}发布于 2017-09-27 13:43:50
保存每个客户端指针以进一步响应。
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();
}
}注:
这只是一个简单的解决方案,以显示保存对象的引用,这些对象是在作用域中创建的,以后应该引用。
如果您想实践更复杂的服务器/客户端应用程序,最好先看看线程“财富”服务器示例和财富客户端示例
https://stackoverflow.com/questions/46448936
复制相似问题