![](/img/trans.png)
[英]qt.network.ssl: QSslSocket::connectToHostEncrypted: TLS initialization failed
[英]Ssl Server using QSslSocket in Qt
我已經使用QSslSocket實現了ssl服務器並正確運行。 但是我有一個問題,我無法立即解決。 我以為只要將readyRead()信號連接到用於讀取緩沖區的插槽就足以做到這一點,但是我已經意識到在這種情況下readyRead()根本不會發出,我還必須在代碼中使用waitForReadyRead()函數。 但是問題是使用此功能導致阻塞讀取緩沖區。 其實我想知道如何在數據到達時不阻塞地讀取緩沖區?
貝婁是我實現的ssl服務器:
#include "sslserver.h"
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QFile>
#include <QtNetwork/QSslKey>
#include <QtNetwork/QSslConfiguration>
#include <QtNetwork/QSslError>
SslServer::SslServer(QObject *parent) : QTcpServer(parent)
{
server = new QTcpServer(this);
if(!server->listen(QHostAddress::Any, 9996))
{
qDebug() << "Server could not start";
}
else
{
qDebug() << "Server started!";
}
connect(server, SIGNAL(newConnection()), this, SLOT(newConnectionRecognized()));
}
void SslServer::showErrors()
{
this-> err = socket->sslErrors();
for(int i=0;i<err.size();i++)
qDebug() << err[i];
}
SslServer::~SslServer()
{
}
void SslServer::newConnectionRecognized()
{
incomingConnection(server->nextPendingConnection()->socketDescriptor());
}
void SslServer::incomingConnection(qintptr socketDescriptor)
{
socket = new QSslSocket(this);
socket->setProtocol(QSsl::SslV3);
connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(showErrors()));
connect(socket, SIGNAL(encrypted()), this, SLOT(ready()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readChannel()));
// Read Key from file
QByteArray key;
QFile KeyFile("server.key");
if(KeyFile.open(QIODevice::ReadOnly))
{
key = KeyFile.readAll();
KeyFile.close();
}
else
{
qDebug() << KeyFile.errorString();
}
QSslKey sslKey(key, QSsl::Rsa);
socket->setPrivateKey(sslKey);
// Load server ssl certificate from file
QByteArray cert;
QFile CertFile("server.csr");
if(CertFile.open(QIODevice::ReadOnly))
{
cert = CertFile.readAll();
CertFile.close();
}
else
{
qDebug() << CertFile.errorString();
}
QSslCertificate sslCert(cert);
socket->setLocalCertificate(sslCert);
QSslConfiguration cfg = socket->sslConfiguration();
cfg.caCertificates();
if (!socket->setSocketDescriptor(socketDescriptor))ee
{
qDebug() << ("! Couldn't set socket descriptor");
delete socket;
return;
}
socket->startServerEncryption();
if (socket->isEncrypted())
emit socket->encrypted();
if(!socket->waitForEncrypted(3000)) {
qDebug("Wait for encrypted!!!!");
return;
}
while (true) {
socket->waitForReadyRead();
}
}
void SslServer::readChannel()
{
QByteArray qstrbytes = socket->readLine();
qDebug() << qstrbytes;
}
void SslServer::ready()
{
qDebug() << "Encrypted";
}
我在實現另一個客戶端/服務器時發現了問題,但是這次使用QTcpSocket。 我不知道為什么,但是我想問題是因為使用socketDescriptor創建了QSslSocket。 當我使用QTcpSocket創建客戶端和服務器時,它們可以完美地運行而沒有任何事件循環,並且只需將readyRead()信號連接到插槽即可。 之后,為了測試某些情況,我使用socketDescriptor創建了QTcpSocket。 然后我發現問題出在使用socketDescriptor創建套接字,因為這一次readyRead()信號無法像以前那樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.