用qt写一个多客户端连接服务端的代码
时间: 2024-05-30 21:14:17 浏览: 109
好的,以下是可以给您提供参考的Qt代码:
// Server端代码
#include <QTcpServer>
#include <QTcpSocket>
QTcpServer *server;
QList<QTcpSocket *> clients;
void newConnection()
{
QTcpSocket *client = server->nextPendingConnection();
clients.append(client);
connect(client, &QTcpSocket::readyRead, [client]() {
QByteArray data = client->readAll();
// 处理客户端发送的数据
});
connect(client, &QTcpSocket::disconnected, [client]() {
clients.removeOne(client);
client->deleteLater();
});
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
server = new QTcpServer(&app);
if (!server->listen(QHostAddress::Any, 1234)) {
qWarning() << "Failed to start server:" << server->errorString();
return 1;
} else {
qDebug() << "Server started!";
}
connect(server, &QTcpServer::newConnection, newConnection);
return app.exec();
}
// Client端代码
#include <QTcpSocket>
QTcpSocket *socket;
void connected()
{
qDebug() << "Connected to server!";
}
void disconnected()
{
qDebug() << "Disconnected from server!";
}
void readyRead()
{
QByteArray data = socket->readAll();
// 处理从服务器接收到的数据
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
socket = new QTcpSocket(&app);
connect(socket, &QTcpSocket::connected, connected);
connect(socket, &QTcpSocket::disconnected, disconnected);
connect(socket, &QTcpSocket::readyRead, readyRead);
socket->connectToHost("127.0.0.1", 1234);
return app.exec();
}
希望能帮到您!
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)