以下是一个简单的示例代码,展示了如何使用QTcpServer创建一个基本的TCP服务器:
”`cpp
#include
class MyServer : public QTcpServer {
Q_OBJECT
public:
MyServer(QObject *parent = nullptr)
: QTcpServer(parent)
{
// 监听指定端口
listen(QHostAddress::Any, 12345);
qDebug() << "Server started";
}
protected:
void incomingConnection(qintptr socketDescriptor) override
{
// 创建一个新的socket连接
QTcpSocket *clientSocket = new QTcpSocket(this);
// 设置套接字描述符
clientSocket->setSocketDescriptor(socketDescriptor);
// 连接信号和槽函数
connect(clientSocket, &QTcpSocket::readyRead, this, &MyServer::readData);
connect(clientSocket, &QTcpSocket::disconnected, this, &MyServer::disconnectClient);
qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
// 向客户端发送欢迎消息
QString welcomeMsg = "Welcome to the server!";
clientSocket->write(welcomeMsg.toUtf8());
}
private slots:
void readData()
{
QTcpSocket *clientSocket = static_cast<QTcpSocket*>(sender());
while (clientSocket->bytesAvailable() > 0)
{
QByteArray data = clientSo<br/><br/><br/><font size=1 color=#CCCCCC>内容由零声教学AI助手提供,问题来源于学员提问</font>