本文整理汇总了C++中QSslSocket类的典型用法代码示例。如果您正苦于以下问题:C++ QSslSocket类的具体用法?C++ QSslSocket怎么用?C++ QSslSocket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QSslSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QSslSocket
void HttpsServer::incomingConnection(qintptr socketDescriptor)
#endif
{
QSslSocket* sslSocket = new QSslSocket(this);
if (sslSocket->setSocketDescriptor(socketDescriptor))
{
sslSocket->setPrivateKey(privateKey());
sslSocket->setLocalCertificate(certificate());
sslSocket->startServerEncryption();
connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslSocket_sslErrors(QList<QSslError>)));
connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocket_encrypted()));
addPendingConnection(sslSocket);
nextPendingConnection();
createHttpConnection()->initialize(sslSocket, sslSocket);
}
else
{
qWarning() << "HttpsServer::incomingConnection: failed to set socket descriptor '" << socketDescriptor << "' on ssl socket.";
delete sslSocket;
}
}
示例2: assert
// Accept connection from server and initiate the SSL handshake
void Server::acceptConnection()
{
if (sockets.empty() == false)
std::cout << "Server is mad efor 1 connection also. Need to update to handle multiple connections" << std::endl;
QSslSocket *socket = dynamic_cast<QSslSocket *>(server.nextPendingConnection());
assert(socket);
// Report any SSL errors that occur
connect(socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionFailure()));
// QSslSocket emits the encrypted() signal after the encrypted connection is established
#define _USE_ENCRYPTION
#ifdef _USE_ENCRYPTION
connect(socket, SIGNAL(encrypted()), this, SLOT(handshakeComplete()));
socket->setPrivateKey(key);
socket->setLocalCertificate(certificate);
socket->setPeerVerifyMode(QSslSocket::VerifyNone);
socket->startServerEncryption();
#else
connect(socket, SIGNAL(disconnected()), this, SLOT(connectionClosed()));
connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
sockets.push_back(socket);
std::cout << "Accepted connection from " << socket->peerAddress().toString().toStdString() << ":" << socket->peerPort() << " .Encrypted : " << socket->isEncrypted() << std::endl;
#endif
}
示例3: WebSocket
//=======================
// PRIVATE SLOTS
//=======================
//GENERIC SERVER SIGNALS
// New Connection Signals
void WebServer::NewSocketConnection(){
WebSocket *sock = 0;
if(WSServer!=0){
if(WSServer->hasPendingConnections()){
QWebSocket *ws = WSServer->nextPendingConnection();
if( !allowConnection(ws->peerAddress()) ){ ws->close(); }
else{ sock = new WebSocket( ws, generateID(), AUTH); }
}
}else if(TCPServer!=0){
if(TCPServer->hasPendingConnections()){
QSslSocket *ss = TCPServer->nextPendingConnection();
if( !allowConnection(ss->peerAddress()) ){ ss->close(); }
else{ sock = new WebSocket( ss, generateID(), AUTH); }
}
}
if(sock==0){ return; } //no new connection
qDebug() << "New Socket Connection";
connect(sock, SIGNAL(SocketClosed(QString)), this, SLOT(SocketClosed(QString)) );
connect(EVENTS, SIGNAL(NewEvent(EventWatcher::EVENT_TYPE, QJsonValue)), sock, SLOT(EventUpdate(EventWatcher::EVENT_TYPE, QJsonValue)) );
connect(sock, SIGNAL(BlackListAddress(QHostAddress)), this, SLOT(BlackListConnection(QHostAddress)) );
OpenSockets << sock;
}
示例4: out
void Server::sendFortune()
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
qDebug() << "In sendFortune";
out << (quint16)0;
out << fortunes.at(qrand() % fortunes.size());
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
QSslSocket *clientConnection = sslServer->nextPendingConnection();
if (!clientConnection->waitForEncrypted(1000)){
qDebug() << "Waited for 1 second for encryption handshake without success";
return;
}
qDebug() << "Successfully waited for secure handshake...";
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
clientConnection->write(block);
clientConnection->disconnectFromHost();
}
示例5: QSslSocket
/*!
Called when a new connection is established.
Converts \a socket to a QSslSocket.
\internal
*/
void QSslServer::incomingConnection(qintptr socket)
{
QSslSocket *pSslSocket = new QSslSocket();
if (Q_LIKELY(pSslSocket)) {
pSslSocket->setSslConfiguration(m_sslConfiguration);
if (Q_LIKELY(pSslSocket->setSocketDescriptor(socket))) {
connect(pSslSocket, &QSslSocket::peerVerifyError, this, &QSslServer::peerVerifyError);
typedef void (QSslSocket::* sslErrorsSignal)(const QList<QSslError> &);
connect(pSslSocket, static_cast<sslErrorsSignal>(&QSslSocket::sslErrors),
this, &QSslServer::sslErrors);
connect(pSslSocket, &QSslSocket::encrypted, this, &QSslServer::newEncryptedConnection);
addPendingConnection(pSslSocket);
pSslSocket->startServerEncryption();
} else {
delete pSslSocket;
}
}
}
示例6: QString
void QuazaaIRC::startIrc()
{
systemLog.postLog(LogSeverity::Debug, QString("QuazaaIRC::startIRC() %1").arg(quazaaSettings.Chat.IrcServerName));
//qDebug() << "QuazaaIRC::startIrc() " << ircServer;
ircSession = new Irc::Session(this);
sServer = quazaaSettings.Chat.IrcServerName;
bLoginCompleted = false;
// stripNicks / echoMessages
ircSession->setOptions(Irc::Session::EchoMessages);
if (quazaaSettings.Chat.IrcUseSSL)
{
QSslSocket* socket = new QSslSocket(ircSession);
socket->ignoreSslErrors();
socket->setPeerVerifyMode(QSslSocket::VerifyNone);
ircSession->setSocket(socket);
}
ircSession->setObjectName("IrcSession");
connect(ircSession, SIGNAL(connected()), this, SLOT(on_IrcSession_connected()));
connect(ircSession, SIGNAL(disconnected()), this, SLOT(on_IrcSession_disconnected()));
connect(ircSession, SIGNAL(welcomed()), this, SLOT(on_IrcSession_welcomed()));
connect(ircSession, SIGNAL(bufferAdded(Irc::Buffer*)), this, SLOT(on_IrcSession_bufferAdded(Irc::Buffer*)));
connect(ircSession, SIGNAL(bufferRemoved(Irc::Buffer*)), this, SLOT(on_IrcSession_bufferRemoved(Irc::Buffer*)));
ircSession->setNick(quazaaSettings.Profile.IrcNickname);
sNick = quazaaSettings.Profile.IrcNickname;
ircSession->setIdent("QuazaaIRC");
ircSession->setRealName(quazaaSettings.Profile.RealName);
sRealName = quazaaSettings.Profile.RealName;
ircSession->setAutoJoinChannels(quazaaSettings.Chat.AutoJoinChannels);
ircSession->connectToServer(quazaaSettings.Chat.IrcServerName, quazaaSettings.Chat.IrcServerPort);
}
示例7: delayedStart
void SslTlsSocket::delayedStart()
{
QSslSocket *sock = qobject_cast<QSslSocket *>(d);
Q_ASSERT(sock);
switch (m_proxySettings) {
case Streams::ProxySettings::RespectSystemProxy:
{
QNetworkProxy setting;
QNetworkProxyQuery query = QNetworkProxyQuery(host, port, m_protocolTag, QNetworkProxyQuery::TcpSocket);
// set to true if a capable setting is found
bool capableSettingFound = false;
// set to true if at least one valid setting is found
bool settingFound = false;
// FIXME: this static function works particularly slow in Windows
QList<QNetworkProxy> proxySettingsList = QNetworkProxyFactory::systemProxyForQuery(query);
/* Proxy Settings are read from the user's environment variables by the above static method.
* A peculiar case is with *nix systems, where an undefined environment variable is returned as
* an empty string. Such entries *might* exist in our proxySettingsList, and shouldn't be processed.
* One good check is to use hostName() of the QNetworkProxy object, and treat the Proxy Setting as invalid if
* the host name is empty. */
Q_FOREACH (setting, proxySettingsList) {
if (!setting.hostName().isEmpty()) {
settingFound = true;
// now check whether setting has capabilities
if (setting.capabilities().testFlag(QNetworkProxy::TunnelingCapability)) {
sock->setProxy(setting);
capableSettingFound = true;
break;
}
}
}
if (!settingFound || proxySettingsList.isEmpty()) {
sock->setProxy(QNetworkProxy::NoProxy);
} else if (!capableSettingFound) {
emit disconnected(tr("The underlying socket is having troubles when processing connection to %1:%2: %3")
.arg(host, QString::number(port), QStringLiteral("Cannot find proxy setting capable of tunneling")));
}
break;
}
case Streams::ProxySettings::DirectConnect:
sock->setProxy(QNetworkProxy::NoProxy);
break;
}
if (startEncrypted)
sock->connectToHostEncrypted(host, port);
else
sock->connectToHost(host, port);
}
示例8: serverDisconnectWithBuffered
// Test buffered socket being properly closed on remote disconnect
void tst_QAbstractSocket::serverDisconnectWithBuffered()
{
QTcpServer tcpServer;
#ifndef QT_NO_SSL
QSslSocket testSocket;
#else
QTcpSocket testSocket;
#endif
QVERIFY(tcpServer.listen(QHostAddress::LocalHost));
testSocket.connectToHost(tcpServer.serverAddress(), tcpServer.serverPort());
// Accept connection on server side
QVERIFY(tcpServer.waitForNewConnection(5000));
QTcpSocket *newConnection = tcpServer.nextPendingConnection();
// Send one char and drop link
QVERIFY(newConnection != NULL);
QVERIFY(newConnection->putChar(0));
QVERIFY(newConnection->flush());
delete newConnection;
QVERIFY(testSocket.waitForConnected(5000)); // ready for write
QVERIFY(testSocket.state() == QAbstractSocket::ConnectedState);
QSignalSpy spyStateChanged(&testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
QSignalSpy spyDisconnected(&testSocket, SIGNAL(disconnected()));
QVERIFY(testSocket.waitForReadyRead(5000)); // have one char already in internal buffer
char buf[128];
QCOMPARE(testSocket.read(buf, sizeof(buf)), Q_INT64_C(1));
if (testSocket.state() != QAbstractSocket::UnconnectedState) {
QVERIFY(testSocket.waitForDisconnected(5000));
QVERIFY(testSocket.state() == QAbstractSocket::UnconnectedState);
}
// Test signal emitting
QVERIFY(spyDisconnected.count() == 1);
QVERIFY(spyStateChanged.count() > 0);
QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
== QAbstractSocket::UnconnectedState);
}
示例9: connectError
void LanLinkProvider::connectError()
{
QSslSocket* socket = qobject_cast<QSslSocket*>(sender());
if (!socket) return;
disconnect(socket, SIGNAL(connected()), this, SLOT(connected()));
disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError()));
qCDebug(KDECONNECT_CORE) << "Fallback (1), try reverse connection (send udp packet)" << socket->errorString();
NetworkPackage np("");
NetworkPackage::createIdentityPackage(&np);
np.set("tcpPort", mTcpPort);
mUdpSocket.writeDatagram(np.serialize(), receivedIdentityPackages[socket].sender, port);
//The socket we created didn't work, and we didn't manage
//to create a LanDeviceLink from it, deleting everything.
delete receivedIdentityPackages.take(socket).np;
delete socket;
}
示例10: QSslSocket
void SslServer::newConnectionPrivate(qintptr descriptor)
{
QSslSocket *socket = new QSslSocket(this);
socket->setSocketDescriptor(descriptor);
if (m_max_connections == 0)
{
socket->abort();
return;
}
socket->setProtocol(QSsl::TlsV1_2OrLater);
socket->addCaCertificate(m_cert);
socket->setLocalCertificate(m_cert);
socket->setPrivateKey(m_key);
//New connection done, set one less available connection
m_max_connections--;
QByteArray m_buffer;
qint32 size = 0;
m_socket_list.append(socket);
m_descriptor_hash.insert(socket, descriptor);
m_socket_hash.insert(descriptor, socket);
m_buffer_hash.insert(socket, m_buffer);
m_size_hash.insert(socket, size);
connect(socket, &QSslSocket::encrypted, this, &SslServer::encrypted);
connect(socket, &QSslSocket::disconnected, this, &SslServer::disconnectedPrivate);
connect(socket, static_cast<void(QSslSocket::*)(const QList<QSslError>&)>(&QSslSocket::sslErrors), this, &SslServer::sslErrors);
m_alive_hash[socket].start();
socket->startServerEncryption();
}
示例11: readyReadPrivate
void SslServer::readyReadPrivate()
{
QSslSocket *socket = qobject_cast<QSslSocket*>(sender());
if (!socket)
return;
QByteArray *m_buffer = &m_buffer_hash[socket];
qint32 &m_size = m_size_hash[socket];
while (socket->bytesAvailable() > 0)
{
m_buffer->append(socket->readAll());
while ((m_size == 0 && m_buffer->size() >= 4) || (m_size > 0 && m_buffer->size() >= m_size))
{
if (m_size == 0 && m_buffer->size() >= 4)
{
m_size = getValue<qint32>(m_buffer->mid(0, 4));
m_buffer->remove(0, 4);
if (m_size < 0 || m_size > MAX_NETWORK_CHUNK_SIZE)
{
socket->abort();
return;
}
}
if (m_size > 0 && m_buffer->size() >= m_size)
{
QByteArray data = m_buffer->mid(0, m_size);
m_buffer->remove(0, m_size);
m_size = 0;
QHostAddress host = socket->peerAddress();
qintptr descriptor = socket->socketDescriptor();
PeerData pd;
pd.data = data;
pd.host = host;
pd.descriptor = descriptor;
QMetaObject::invokeMethod(this, "process", Qt::QueuedConnection, Q_ARG(PeerData, pd));
}
}
}
}
示例12: incomingConnection
void SSLServer::incomingConnection(int socketDescriptor)
{
// On an incoming connection we want
// to create a new secure socket.
QSslSocket *secureSocket = new QSslSocket;
// Add to list so that we can find it with
// nextConnection
m_secureSocketList.append(secureSocket);
// We need to read in the local certificate and
// and the private key that we generated
// with openssl. Read the README to see
// how these are generated.
secureSocket->setLocalCertificate("cacert.pem");
secureSocket->setPrivateKey("privkey.pem");
// check that the certificate / private key are not null
if (secureSocket->localCertificate().isNull()) {
qDebug() << "WARNING: The local certificate appears to be null! ";
}
if (secureSocket->privateKey().isNull()) {
qDebug() << "WARNING: The private key appears to be null! ";
}
// debug message on success
qDebug() << "Created the SSL socket, Read local cert. / private key files";
// From incoming connection we obtain the socket descriptor,
// we associate this with our new SSL socket
secureSocket->setSocketDescriptor(socketDescriptor);
// Begin encryption. Note from the documentation
// all the key stuff must be done prior to doing this.
secureSocket->startServerEncryption();
qDebug() << "Started encryption for new secure socket";
}
示例13: switch
void SslServer::process(const PeerData &pd)
{
QByteArray data = pd.data;
if (data.isEmpty())
return;
quint8 command = getValue<quint8>(data.mid(0, 1));
data.remove(0, 1);
QSslSocket *socket = m_socket_hash[pd.descriptor];
if (!socket)
return;
switch (command)
{
case ServerCommand::PeerTryConnect:
{
if (data.size() != 20)
{
removeSocket(socket);
return;
}
QByteArray peer_id = data;
peer_id = cleanString(QLatin1String(peer_id)).toLatin1().leftJustified(peer_id.length(), char(0), true);
if (m_unavailable_list.contains(peer_id))
{
DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
<< "User target:" << qPrintable(peer_id) << "Attempt to connect to unavailable user!");
writeWarning(socket, "You're trying to connect to a unavailable user!");
return;
}
if (peer_id == m_id_hash[socket])
{
DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
<< "User target:" << qPrintable(peer_id) << "Attempt to connect to itself!");
writeWarning(socket, "You're trying to connect to itself!");
return;
}
if (!m_id_list.contains(peer_id))
{
DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
<< "User target:" << qPrintable(peer_id) << "Attempt to connect to non connected user!");
writeWarning(socket, "You're trying to connect to a non connected user!");
return;
}
QSslSocket *target_socket = m_id_hash.key(peer_id);
if (m_connecting_connected_list.contains(target_socket))
{
DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
<< "User target:" << qPrintable(peer_id) << "Attempt to connect to already connected user!");
writeWarning(socket, "User already connected!");
return;
}
m_connecting_connected_list.append(socket);
m_connecting_connected_list.append(target_socket);
QByteArray data;
data.append(getBytes<quint8>(ServerCommand::ConnectionRequested));
data.append(getBytes<quint32>(socket->localAddress().toIPv4Address()));
data.append(m_id_hash[socket]);
m_accept_hash.insert(target_socket, socket);
DEBUG_FUNCTION("IP:" << qPrintable(socket->peerAddress().toString()) << "User origin:" << qPrintable(m_id_hash.value(socket))
<< "User target:" << qPrintable(peer_id) << "Trying to connect to peer!");
target_socket->write(getBytes<qint32>(data.size()));
target_socket->write(data);
break;
}
case ServerCommand::ConnectionAnswer:
{
if (data.size() != 1)
{
removeSocket(socket);
return;
}
QSslSocket *socket_starter = m_accept_hash[socket];
bool accepted = getValue<bool>(data.mid(0, 1));
if (!socket_starter)
{
m_connecting_connected_list.removeAll(socket_starter);
m_connecting_connected_list.removeAll(socket);
if (accepted)
{
//.........这里部分代码省略.........
示例14: SIGNAL
void QHttpNetworkConnectionChannel::init()
{
#ifndef QT_NO_SSL
if (connection->d_func()->encrypt)
socket = new QSslSocket;
else
socket = new QTcpSocket;
#else
socket = new QTcpSocket;
#endif
#ifndef QT_NO_BEARERMANAGEMENT
//push session down to socket
if (networkSession)
socket->setProperty("_q_networksession", QVariant::fromValue(networkSession));
#endif
#ifndef QT_NO_NETWORKPROXY
// Set by QNAM anyway, but let's be safe here
socket->setProxy(QNetworkProxy::NoProxy);
#endif
QObject::connect(socket, SIGNAL(bytesWritten(qint64)),
this, SLOT(_q_bytesWritten(qint64)),
Qt::DirectConnection);
QObject::connect(socket, SIGNAL(connected()),
this, SLOT(_q_connected()),
Qt::DirectConnection);
QObject::connect(socket, SIGNAL(readyRead()),
this, SLOT(_q_readyRead()),
Qt::DirectConnection);
// The disconnected() and error() signals may already come
// while calling connectToHost().
// In case of a cached hostname or an IP this
// will then emit a signal to the user of QNetworkReply
// but cannot be caught because the user did not have a chance yet
// to connect to QNetworkReply's signals.
qRegisterMetaType<QAbstractSocket::SocketError>();
QObject::connect(socket, SIGNAL(disconnected()),
this, SLOT(_q_disconnected()),
Qt::QueuedConnection);
QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(_q_error(QAbstractSocket::SocketError)),
Qt::QueuedConnection);
#ifndef QT_NO_NETWORKPROXY
QObject::connect(socket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
this, SLOT(_q_proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
Qt::DirectConnection);
#endif
#ifndef QT_NO_SSL
QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket);
if (sslSocket) {
// won't be a sslSocket if encrypt is false
QObject::connect(sslSocket, SIGNAL(encrypted()),
this, SLOT(_q_encrypted()),
Qt::DirectConnection);
QObject::connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(_q_sslErrors(QList<QSslError>)),
Qt::DirectConnection);
QObject::connect(sslSocket, SIGNAL(encryptedBytesWritten(qint64)),
this, SLOT(_q_encryptedBytesWritten(qint64)),
Qt::DirectConnection);
if (ignoreAllSslErrors)
sslSocket->ignoreSslErrors();
if (!ignoreSslErrorsList.isEmpty())
sslSocket->ignoreSslErrors(ignoreSslErrorsList);
if (!sslConfiguration.isNull())
sslSocket->setSslConfiguration(sslConfiguration);
}
#endif
#ifndef QT_NO_NETWORKPROXY
if (proxy.type() != QNetworkProxy::NoProxy)
socket->setProxy(proxy);
#endif
isInitialized = true;
}
示例15: QSslSocket
void WebSocketWorker::SetupSocket()
{
if (m_connectionType == kSSLServer)
{
#ifndef QT_NO_OPENSSL
QSslSocket *pSslSocket = new QSslSocket();
if (pSslSocket->setSocketDescriptor(m_socketFD)
&& gCoreContext->CheckSubnet(pSslSocket))
{
pSslSocket->setSslConfiguration(m_sslConfig);
pSslSocket->startServerEncryption();
if (pSslSocket->waitForEncrypted(5000))
{
LOG(VB_HTTP, LOG_INFO, "SSL Handshake occurred, connection encrypted");
LOG(VB_HTTP, LOG_INFO, QString("Using %1 cipher").arg(pSslSocket->sessionCipher().name()));
}
else
{
LOG(VB_HTTP, LOG_WARNING, "SSL Handshake FAILED, connection terminated");
delete pSslSocket;
pSslSocket = nullptr;
}
}
else
{
delete pSslSocket;
pSslSocket = nullptr;
}
if (pSslSocket)
m_socket = dynamic_cast<QTcpSocket *>(pSslSocket);
else
return;
#else
return;
#endif
}
else // Plain old unencrypted socket
{
m_socket = new QTcpSocket();
m_socket->setSocketDescriptor(m_socketFD);
if (!gCoreContext->CheckSubnet(m_socket))
{
delete m_socket;
m_socket = nullptr;
return;
}
}
m_socket->setSocketOption(QAbstractSocket::KeepAliveOption, QVariant(1));
connect(m_socket, SIGNAL(readyRead()), SLOT(doRead()));
connect(m_socket, SIGNAL(disconnected()), SLOT(CloseConnection()));
// Setup heartbeat
m_heartBeat->setInterval(20000); // 20 second
m_heartBeat->setSingleShot(false);
connect(m_heartBeat, SIGNAL(timeout()), SLOT(SendHeartBeat()));
}