用QWebSocketServer来构建一个服务器,实现给连接它的各个客户端发送消息

先把界面画出来如图:

 创建服务网和监听:

    WebSocketServer = new QWebSocketServer(QStringLiteral("testServer"),QWebSocketServer::NonSecureMode,this);
    //QWebSocketServer::SslMode 运行模式:安全模式(SecureMode)wss,非安全模式(NonSecureMode)ws
    connect(WebSocketServer, &QWebSocketServer::newConnection, this, &Widget::getNewConnection);
    WebSocketServer->listen(QHostAddress::Any,9906);

监听9906端口,其中 QWebSocketServer::SslMode 是运行模式,有两种:安全模式(SecureMode)wss,非安全模式(NonSecureMode)ws,这里使用非安全模式构建

当有新连接过来时的处理

void Widget::getNewConnection()
{
    if(WebSocketServer->hasPendingConnections()) //有未处理的连接
    {
        QWebSocket * webSocket = WebSocketServer->nextPendingConnection();
        ui->textEdit->append(webSocket->origin() + "连接上了");
        webSocketList << webSocket;

        QListWidgetItem * item = new QListWidgetItem;
        item->setText(webSocket->origin());
        ui->listWidget->addItem(item);

        connect(webSocket,&QWebSocket::disconnected,this,[webSocket,this]
        {
            ui->textEdit->append(webSocket->origin() + "断开连接了");
            webSocketList.removeOne(webSocket);
            for (int j = 0; j < ui->listWidget->count(); j++)
            {
                QListWidgetItem * item = ui->listWidget->item(j);
                if (item->text() == webSocket->origin())
                {
                    ui->listWidget->removeItemWidget(item);
                    delete item;
                    break;
                }
            }
            webSocket->deleteLater();
        });

        connect(webSocket,&QWebSocket::textMessageReceived,this,&Widget::ReceivedMsg);
        connect(webSocket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(onError(QAbstractSocket::SocketError)));
    }
}

储存连接的websocket: 

    QList<QWebSocket*> webSocketList;

收到消息和出错时的处理:


void Widget::ReceivedMsg(const QString &message)
{
    QWebSocket * webSocket = qobject_cast<QWebSocket *>(sender());
    ui->textEdit->append("收到消息:" + webSocket->origin() + " - " + message);
}

void Widget::onError(QAbstractSocket::SocketError error)
{
    QWebSocket * webSocket = qobject_cast<QWebSocket *>(sender());
    ui->textEdit->append(webSocket->origin() + "出错" + webSocket->errorString());
}

发送按钮给客户端发送消息,分单个发送还是一起发送:


void Widget::on_pushButton_clicked()
{
    QString text = ui->textEdit_2->toPlainText().trimmed();
    if(text.isEmpty())
        return;

    if(ui->radioButton_all->isChecked())
    {
        if(webSocketList.size() == 0)
            return;

        for (auto socket:webSocketList)
        {
            socket->sendTextMessage(text);
        }
        ui->textEdit->append("服务端给所有连接发送:" + text);
    }
    else
    {
        if(!ui->listWidget->currentItem())
            return;

        QString current = ui->listWidget->currentItem()->text();

        QWebSocket * webSocket = nullptr;
        for (auto socket:webSocketList)
        {
            if(socket->origin() == current)
            {
                webSocket = socket;
                break;
            }
        }
        if(webSocket)
        {
            webSocket->sendTextMessage(text);
            ui->textEdit->append("服务端给" + webSocket->origin() + "发送:" + text);
        }
    }
    ui->textEdit_2->clear();
}

打开命令行,输入“ipconfig”命令

这个地址用来测试的 

代码就这些,来测试一下,百度搜索“websocket在线测试”就会搜出一堆测试网站,随便点进去一个,输入地址:

上面构建的QWebSocketServer是非安全模式的,这里地址以ws开头,地址是自己的IP地址,端口号是上面设置的9906端口。

点击连接按钮

互发消息也能收到

再多连一个客户端,点进另一个websocket测试网页

 服务端也显示连上了

 给所有客户端发消息:

如下图,所有客户端都收到消息了:

 

代码:https://download.csdn.net/download/kenfan1647/12905996 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐