QT实现一个局域网聊天功能客户端和服务端代码
时间: 2023-11-02 08:06:22 浏览: 119
QT实现的局域网聊天工具
5星 · 资源好评率100%
以下是一个基于QT的简单局域网聊天程序的客户端和服务端代码:
服务端代码:
```
#include <QTcpSocket>
#include <QTcpServer>
#include <QNetworkInterface>
#include <QHostAddress>
QTcpServer *server;
QTcpSocket *socket;
void sendMessage(QString message)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out << message.size();
out << message;
socket->write(block);
}
void newConnection()
{
socket = server->nextPendingConnection();
QObject::connect(socket, &QTcpSocket::readyRead, []() {
QDataStream in(socket);
if (socket->bytesAvailable() < (int)sizeof(quint16))
return;
quint16 blockSize;
in >> blockSize;
if (socket->bytesAvailable() < blockSize)
return;
QString message;
in >> message;
// handle message
});
}
void startServer()
{
server = new QTcpServer();
QObject::connect(server, &QTcpServer::newConnection, newConnection);
if (!server->listen(QHostAddress::Any, 12345)) {
qDebug() << "failed to start server";
return;
}
qDebug() << "server started";
}
void sendMessageToAll(QString message)
{
for (auto socket : server->children()) {
if (QTcpSocket *client = qobject_cast<QTcpSocket *>(socket)) {
sendMessage(message);
}
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
startServer();
return a.exec();
}
```
客户端代码:
```
#include <QTcpSocket>
#include <QDataStream>
QTcpSocket *socket;
void connectToServer()
{
socket = new QTcpSocket();
socket->connectToHost(QHostAddress("127.0.0.1"), 12345);
QObject::connect(socket, &QTcpSocket::connected, []() {
qDebug() << "connected to server";
});
QObject::connect(socket, &QTcpSocket::readyRead, []() {
QDataStream in(socket);
if (socket->bytesAvailable() < (int)sizeof(quint16))
return;
quint16 blockSize;
in >> blockSize;
if (socket->bytesAvailable() < blockSize)
return;
QString message;
in >> message;
// handle message
});
}
void sendMessage(QString message)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out << message.size();
out << message;
socket->write(block);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
connectToServer();
sendMessage("hello world");
return a.exec();
}
```
以上代码实现了一个简单的局域网聊天程序,服务端监听端口等待连接,客户端连接到服务端并发送消息,服务端接收消息并处理。客户端和服务端代码中都实现了发送消息的函数 `sendMessage`,使用 `QDataStream` 对消息进行序列化,并使用 `QTcpSocket` 发送和接收数据。
阅读全文