QT实现一个多人聊天系统客户端和服务端代码
时间: 2023-11-03 16:05:41 浏览: 242
以下是一个基于QT的多人聊天系统客户端和服务端的示例代码:
服务端代码:
```cpp
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QVector>
int main(int argc, char *argv[])
{
QTcpServer server;
QVector<QTcpSocket*> clients;
QObject::connect(&server, &QTcpServer::newConnection, [&](){
QTcpSocket* client = server.nextPendingConnection();
clients.append(client);
QObject::connect(client, &QTcpSocket::readyRead, [=](){
QByteArray data = client->readAll();
for(QTcpSocket* otherClient : clients)
{
if(otherClient != client)
otherClient->write(data);
}
});
QObject::connect(client, &QTcpSocket::disconnected, [=](){
clients.removeOne(client);
client->deleteLater();
});
});
if(server.listen(QHostAddress::Any, 1234))
qDebug() << "Server started";
else
qDebug() << "Server failed to start";
return 0;
}
```
客户端代码:
```cpp
#include <QtNetwork/QTcpSocket>
int main(int argc, char *argv[])
{
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 1234);
QObject::connect(&socket, &QTcpSocket::readyRead, [&](){
QByteArray data = socket.readAll();
qDebug() << data;
});
QTextStream stream(stdin);
while(true)
{
QString message = stream.readLine();
socket.write(message.toUtf8());
}
return 0;
}
```
这个示例代码比较简单,服务端只是简单地把接收到的消息广播给所有连接的客户端,而客户端只是简单地从标准输入读取消息并发送给服务端,然后从服务端接收消息并输出到控制台。在实际的应用中,还需要考虑很多其他的问题,比如消息的格式、用户登录、用户列表、私聊等等。
阅读全文