本文整理汇总了C++中QTcpSocket类的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket类的具体用法?C++ QTcpSocket怎么用?C++ QTcpSocket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QTcpSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: debugInfo
void Server::acceptUser() {
//to be called every time a new connection is received
QTcpSocket *socket = m_tcp_server->nextPendingConnection();
debugInfo("New incoming connection, from IP " +
socket->peerAddress().toString() +
" and port: " + QString::number(socket->peerPort()));
//check if ip is registered
if (!isThisIpRegistered(socket->peerAddress().toString())) {
//then parse user
UE new_ue;
new_ue.name = "";
new_ue.ip = socket->peerAddress().toString();
//will change when ue_name() is sent
new_ue.rx_port = 0;
m_online_users.append(new_ue);
debugInfo("New empty UE registered!");
} else {
debugInfo("user is transmitting either its name or data");
socket->waitForReadyRead(1000);
//parse data
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_0);
debugInfo("m_block_size: " + QString::number(m_block_size));
if (m_block_size == 0) {
if (socket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> m_block_size;
}
debugInfo("bytes available in socket: " + QString::number(socket->bytesAvailable()));
if (socket->bytesAvailable() < m_block_size)
return;
QString message;
in >> message;
debugInfo(">Message: [" + message + "]");
ProtocolStreamType_UE type;
QStringList params = m_protocol->parseStream_UE(type, message);
switch (type) {
case UE_REGISTER:
{
QString temp_name = params.at(0);
quint16 temp_port = (quint16) params.at(1).toInt();
DLOG (INFO) << "Parsed port: " << temp_port;
if (temp_name.isEmpty()) {
m_block_size=0;
return;
}
UE temp;
int index;
if (!isThisNameRegistered(temp_name)) {
//case for same ip, different name
debugInfo("New user " + temp_name + " connected from same IP. Registering user.");
temp.name = temp_name;
temp.ip = socket->peerAddress().toString();
//parse ue_rx_port
temp.rx_port = temp_port;
index = getIndexOfUEIp(socket->peerAddress().toString());
if (m_online_users.at(index).name.isEmpty()) {
//first time, when username is still empty
if (index != -1) {
temp = m_online_users.at(index);
temp.name = temp_name;
temp.rx_port = temp_port;
m_online_users.replace(index,temp);
}
} else {
//same ip but different username, then append new UE
m_online_users.append(temp);
}
} else {
LOG (ERROR) << "User already exists on server. Notifying user...";
//inform user of currently online users
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << QString("ue_error(Existing user on server. Choose other username);");
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
DLOG (INFO) <<"Sending error message to UE ...\n";
m_log_label->setText(m_log_label->toPlainText()
+ "\nError: attempted connection with same "
"username from same IP. Sending error to client...");
socket->write(block);
//reset m_block_size
m_block_size = 0;
return;
}
DLOG (INFO) << "New user is online: " << temp;
debugInfo("Nr. online users: " + QString::number(m_online_users.size()));
if (m_log_label->toPlainText() != "") {
m_log_label->setText(m_log_label->toPlainText() + "\n[" + temp.name + "]@" +
temp.ip + ":" +
QString::number(temp.rx_port) + " is now online.");
} else {
//.........这里部分代码省略.........
示例2: main
int main(int argc, char* argv[])
{
terrama2::core::TerraMA2Init terramaRaii("example", 0);
QCoreApplication app(argc, argv);
QJsonObject obj;
QJsonArray providersArray;
providersArray.push_back(terrama2::core::toJson(buildInputProvider()));
obj.insert("DataProviders", providersArray);
QJsonArray seriesArray;
seriesArray.push_back(terrama2::core::toJson(buildInputDataSeries()));
obj.insert("DataSeries", seriesArray);
QJsonDocument doc(obj);
std::shared_ptr<terrama2::core::DataManager> dataManager = std::make_shared<MockDataManager>();
terrama2::core::TcpManager tcpManager(dataManager, std::weak_ptr<terrama2::core::ProcessLogger>());
tcpManager.listen(QHostAddress::Any, 30000);
QByteArray bytearray;
QDataStream out(&bytearray, QIODevice::WriteOnly);
QJsonObject logDb;
logDb.insert("PG_HOST", QString::fromStdString(TERRAMA2_DATABASE_HOST));
logDb.insert("PG_PORT", QString::fromStdString(TERRAMA2_DATABASE_PORT));
logDb.insert("PG_USER", QString::fromStdString(TERRAMA2_DATABASE_USERNAME));
logDb.insert("PG_PASSWORD", QString::fromStdString(TERRAMA2_DATABASE_PASSWORD));
logDb.insert("PG_DB_NAME", QString::fromStdString(TERRAMA2_DATABASE_DBNAME));
QJsonObject serviceConf;
serviceConf.insert("instance_id", 1);
serviceConf.insert("log_database", logDb);
QJsonDocument serviceConfDoc(serviceConf);
QByteArray serviceConfBytearray;
QDataStream out2(&serviceConfBytearray, QIODevice::WriteOnly);
auto jsonServiceConf = serviceConfDoc.toJson(QJsonDocument::Compact);
out2 << static_cast<uint32_t>(0);
out2 << static_cast<uint32_t>(terrama2::core::TcpSignal::UPDATE_SERVICE_SIGNAL);
out2 << jsonServiceConf;
serviceConfBytearray.remove(8, 4);//Remove QByteArray header
out2.device()->seek(0);
out2 << static_cast<uint32_t>(serviceConfBytearray.size() - sizeof(uint32_t));
auto json = doc.toJson(QJsonDocument::Compact);
out << static_cast<uint32_t>(0);
out << static_cast<uint32_t>(terrama2::core::TcpSignal::ADD_DATA_SIGNAL);
out << json;
bytearray.remove(8, 4);//Remove QByteArray header
out.device()->seek(0);
out << static_cast<uint32_t>(bytearray.size() - sizeof(uint32_t));
QTcpSocket socket;
socket.connectToHost("localhost", 30000);
socket.write(serviceConfBytearray);
socket.waitForBytesWritten();
socket.write(bytearray);
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
timer.start(10000);
app.exec();
return 0;
}
示例3: qDebug
void Tunneld::promiseChannelCleanup(ToxTunChannel *chan)
{
qDebug()<<chan<<sender();
QObject *snderobj = (QObject*)sender();
QTimer *repeat_timer = NULL;
qDebug()<<snderobj->objectName()<<snderobj->metaObject()->className();
if (chan == NULL) {
repeat_timer = (QTimer*)snderobj;
assert(repeat_timer != NULL);
int conid = repeat_timer->property("conid").toInt();
if (!m_conid_chans.contains(conid)) {
qDebug()<<"maybe too late repeat check self sock close timer event";
repeat_timer->deleteLater();
return;
}
chan = m_conid_chans[conid];
assert(chan != NULL);
} else {
// snderobj is ENetPoll or QTcpSocket
}
QTcpSocket *sock = chan->m_sock;
ENetPeer *enpeer = chan->m_enpeer;
//////////
QHash<QString, bool> promise_results;
promise_results["sock_closed"] = chan->sock_closed;
// promise_results["enet_closed"] = chan->enet_closed;
promise_results["peer_sock_closed"] = chan->peer_sock_closed;
bool promise_result = true;
for (auto it = promise_results.begin(); it != promise_results.end(); it ++) {
QString key = it.key();
bool val = it.value();
promise_result = promise_result && val;
}
if (true) {
// 检测对方最近的回包情况
if (!promise_result && repeat_timer == NULL
&& promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
qDebug()<<"here";
if (chan->last_recv_peer_pkt_time == QDateTime()) {
qDebug()<<"maybe can close socket right now, because recv nothing forever";
}
QTimer *t = new QTimer();
t->setInterval(500);
t->setSingleShot(true);
t->setProperty("conid", QVariant(chan->m_conid));
// // QObject::connect(t, &QTimer::timeout, this, &Tunneld::promiseChannelCleanup, Qt::QueuedConnection);
QObject::connect(t, SIGNAL(timeout()), this, SLOT(promiseChannelCleanup()), Qt::QueuedConnection);
qDebug()<<"start repeat check sock close timer:";
t->start();
}
if (!promise_result && repeat_timer != NULL
&& promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
//
QDateTime now_time = QDateTime::currentDateTime();
uint32_t last_recv_to_now_time = chan->last_recv_peer_pkt_time.msecsTo(now_time);
qDebug()<<"here:"<<last_recv_to_now_time<<enpeer->lastReceiveTime;
if (last_recv_to_now_time > 7000) {
qDebug()<<"last recv to now, force close self socket:"<<last_recv_to_now_time
<<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
// 不能直接关闭,要在当前函数执行完后,即下一次事件的时候开始执行。
QTimer::singleShot(1, sock, &QTcpSocket::close);
// QTimer *t = new QTimer();
// t->setSingleShot(true);
// QObject::connect(t, &QTimer::timeout, sock, &QTcpSocket::close, Qt::QueuedConnection);
// t->start(1);
repeat_timer->deleteLater();
} else {
repeat_timer->start();
}
}
}
if (!promise_result) {
qDebug()<<"promise nooooot satisfied:"<<promise_results<<chan->m_conid;
return;
}
chan->promise_close_time = QDateTime::currentDateTime();
qDebug()<<"promise satisfied."<<chan->m_conid;
///// do cleanup
bool force_closed = chan->force_closed;
// enpeer->toxchan = NULL; // cleanup
peerRemoveChan(enpeer, chan);
this->m_sock_chans.remove(sock);
// this->m_enpeer_chans.remove(enpeer);
this->m_conid_chans.remove(chan->m_conid);
delete chan;
sock->disconnect();
sock->deleteLater();
//.........这里部分代码省略.........
示例4: tcpProcessPendingDatagrams
void Widget::tcpProcessPendingDatagrams()
{
// Find who's sending
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket == 0)
return;
unsigned nTries = 0;
// Acquire data
while(socket->state()==QAbstractSocket::ConnectedState && nTries<3) // Exit if disconnected, too much retries, malformed HTTP request, or after all requests are processed
{
tcpReceivedDatas->append(socket->readAll());
nTries++;
if (!tcpReceivedDatas->startsWith("POST") && !tcpReceivedDatas->startsWith("GET")) // Not HTTP, clear the buffer
{
logMessage("TCP: Received non-HTTP request");
tcpReceivedDatas->clear();
socket->close();
return;
}
else if (tcpReceivedDatas->contains("Content-Length:")) // POST or GET request, wait for Content-Length header
{
QByteArray contentLength = *tcpReceivedDatas;
contentLength = contentLength.right(contentLength.size() - contentLength.indexOf("Content-Length:") - 15);
QList<QByteArray> lengthList = contentLength.trimmed().split('\n');
if (lengthList.size()>1) // We want a number on this line and a next line to be sure we've got the full number
{
bool isNumeric;
int length = lengthList[0].trimmed().toInt(&isNumeric);
if (!isNumeric) // We've got something but it's not a number
{
logMessage("TCP: Error: Content-Length must be a (decimal) number !");
tcpReceivedDatas->clear();
socket->close();
return;
}
// Detect and send data files if we need to
QByteArray data = *tcpReceivedDatas;
//logMessage("DataReceived:"+data);
// Get the payload only (remove headers)
data = removeHTTPHeader(data, "POST ");
data = removeHTTPHeader(data, "GET ");
data = removeHTTPHeader(data, "User-Agent:");
data = removeHTTPHeader(data, "Host:");
data = removeHTTPHeader(data, "host:");
data = removeHTTPHeader(data, "Accept:");
data = removeHTTPHeader(data, "Content-Length:");
data = removeHTTPHeader(data, "Content-Type:");
data = removeHTTPHeader(data, "Server:");
data = removeHTTPHeader(data, "Date:");
data = removeHTTPHeader(data, "Transfert-Encoding:");
data = removeHTTPHeader(data, "Connection:");
data = removeHTTPHeader(data, "Vary:");
data = removeHTTPHeader(data, "X-Powered-By:");
data = removeHTTPHeader(data, "accept-encoding:");
data = removeHTTPHeader(data, "if-modified-since:");
if (data.size() >= length) // Wait until we have all the data
{
data.truncate(length);
// Process data, if the buffer is not empty, keep reading
tcpProcessData(data, socket);
// Delete the processed message from the buffer
*tcpReceivedDatas = tcpReceivedDatas->right(tcpReceivedDatas->size() - tcpReceivedDatas->indexOf(data) - data.size());
if (tcpReceivedDatas->isEmpty())
return;
nTries=0;
}
}
}
else if (tcpReceivedDatas->contains("\r\n\r\n")) // POST or GET request, without a Content-Length header
{
QByteArray data = *tcpReceivedDatas;
data = data.left(data.indexOf("\r\n\r\n")+4);
int i1=0;
do
{
i1 = data.indexOf("GET");
if (i1 != -1)
{
int i2 = data.indexOf("HTTP")-1;
QString path = data.mid(i1 + 4, i2-i1-4);
data = removeHTTPHeader(data, "POST ");
data = removeHTTPHeader(data, "GET ");
logMessage("Received GET:"+path);
QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
QFile res("data/"+path);
head.open(QIODevice::ReadOnly);
if (!head.isOpen())
{
logMessage("Can't open header : "+head.errorString());
continue;
}
res.open(QIODevice::ReadOnly);
//.........这里部分代码省略.........
示例5: qWarning
bool ZHttpServer::startServer(quint16 port)
{
if(m_tcpServer->isListening())
return true;
if(!m_tcpServer->listen(QHostAddress::Any, port)){
qWarning() << "HttpServer: error: " << m_tcpServer->errorString();
return false;
}else{
qWarning() << "HttpServer: OK";
}
connect(m_tcpServer, &QTcpServer::newConnection, [this]{
QTcpSocket *socket = m_tcpServer->nextPendingConnection();
qWarning() << "HttpServer: new connect:" << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();
connect(socket, &QTcpSocket::readyRead, [socket, this]{
HttpInfo info(socket->readAll());
qWarning() << info.url();
const QByteArray &query = info.url().query().toUtf8();
QMap<QByteArray, QByteArray> command_map;
QFileInfo fileInfo(sysroot + info.url().path());
if (fileInfo.isFile() && fileInfo.isExecutable()) {
execProcess((fileInfo.fileName() + " " + info.url().query(QUrl::FullyDecoded)).toLatin1(), socket);
return;
}
if(!query.isEmpty()) {
QByteArrayList commands = query.split('&');
qWarning() << "HttpServer: command:" << commands;
for(const QByteArray &comm : commands) {
if(comm.isEmpty())
continue;
const QByteArrayList &tmp_list = comm.split('=');
if(tmp_list.count() != 2 || tmp_list.first().isEmpty()) {
socket->write(messagePackage("", "text/Html", HttpInfo::BadRequest, QString("Grammatical errors: \"%1\"").arg(QString(comm))));
socket->close();
return;
}
command_map[tmp_list.first()] = tmp_list.last();
}
}
if(command_map.value(ACTION) == ACTION_EXEC) {
execProcess(QUrl::fromPercentEncoding(command_map.value(COMMAND)), socket);
} else {
QPointer<QTcpSocket> socket_pointer = socket;
readFile(info.url(), socket);
if (socket_pointer)
socket->close();
}
});
connect(socket, &QTcpSocket::disconnected, [socket]{
qWarning() << "HttpServer: disconnected: " << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();
socket->deleteLater();
});
});
return true;
}
示例6: readClient
/**
* readClient: signal handler for RAOP client connection
* Handle initialisation of session
*/
void MythRAOPConnection::readClient(void)
{
QTcpSocket *socket = (QTcpSocket *)sender();
if (!socket)
return;
QByteArray data = socket->readAll();
LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("readClient(%1): ")
.arg(data.size()) + data.constData());
// For big content, we may be called several times for a single packet
if (!m_incomingPartial)
{
m_incomingHeaders.clear();
m_incomingContent.clear();
m_incomingSize = 0;
QTextStream stream(data);
QString line;
do
{
line = stream.readLine();
if (line.size() == 0)
break;
LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("Header = %1").arg(line));
m_incomingHeaders.append(line);
if (line.contains("Content-Length:"))
{
m_incomingSize = line.mid(line.indexOf(" ") + 1).toInt();
}
}
while (!line.isNull());
if (m_incomingHeaders.size() == 0)
return;
if (!stream.atEnd())
{
int pos = stream.pos();
if (pos > 0)
{
m_incomingContent.append(data.mid(pos));
}
}
}
else
{
m_incomingContent.append(data);
}
// If we haven't received all the content yet, wait (see when receiving
// coverart
if (m_incomingContent.size() < m_incomingSize)
{
m_incomingPartial = true;
return;
}
else
{
m_incomingPartial = false;
}
LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("Content(%1) = %2")
.arg(m_incomingContent.size()).arg(m_incomingContent.constData()));
ProcessRequest(m_incomingHeaders, m_incomingContent);
}
示例7: qDebug
void GroupRequestDlg::slotOkClicked()
{
if (ui_->rb_allow_->isChecked())
{
QString allow_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
"&msg=&op_type=2&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());
Request req;
req.create(kGet, allow_url);
req.addHeaderItem("Host", "d.web2.qq.com");
req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
req.addHeaderItem("Content-Type", "utf-8");
QTcpSocket fd;
fd.connectToHost("d.web2.qq.com", 80);
fd.write(req.toByteArray());
fd.waitForReadyRead();
qDebug()<<"allow add group request: "<<fd.readAll();
accept();
}
else
{
QString deny_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
"&msg=" + ui_->le_deny_reason_->text() + "&op_type=3&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());
Request req;
req.create(kGet, deny_url);
req.addHeaderItem("Host", "d.web2.qq.com");
req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
req.addHeaderItem("Content-Type", "utf-8");
QTcpSocket fd;
fd.connectToHost("d.web2.qq.com", 80);
fd.write(req.toByteArray());
fd.waitForReadyRead();
qDebug()<<"deny add group request"<<fd.readAll();
fd.close();
reject();
}
}
示例8: sender
void PanoServerTCP::IncomingData() {
QTcpSocket* conn = (QTcpSocket*) sender();
vector<TcpConnection>::iterator host = std::find(connections_.begin(),
connections_.end(),
TcpConnection(conn));
if (host == connections_.end()) {
log("Client to registered at TCP server.");
return;
}
if (conn->bytesAvailable() <= 0) {
log("Error on incoming data. Packet is empty!");
return;
}
QByteArray data = conn->readAll();
int data_pos = 0;
// Multiple packages possible.
while (data_pos < data.length()) {
// Continue package?
if (host->pkg.length()) {
int remaining_data_bytes = data.length() - data_pos;
int remaining_bytes = host->target_sz - host->pkg.length();
if (remaining_data_bytes <= remaining_bytes) {
host->pkg.append(data.mid(data_pos, remaining_data_bytes));
data_pos += remaining_data_bytes;
} else {
// Another package is waiting.
host->pkg.append(data.mid(data_pos, remaining_bytes));
data_pos += remaining_bytes;
}
} else {
// New package.
QDataStream data_stream(data.mid(data_pos));
data_stream.setByteOrder(QDataStream::LittleEndian);
int msg_id;
int length;
data_stream >> msg_id;
data_stream >> length;
data_pos += sizeof(int) * 2;
int remaining_data_bytes = data.length() - data_pos;
switch (msg_id) {
case 0x13030002:
{
log("New image uploaded");
// Most likely more packages are incoming ...
host->target_sz = length;
host->msg_id = msg_id;
if (length > remaining_data_bytes) {
host->pkg.append(data.mid(data_pos, remaining_data_bytes));
data_pos += remaining_data_bytes;
} else {
host->pkg.append(data.mid(data_pos, length));
data_pos += length;
}
break;
}
case 0x13030005:
{
// Image lock request.
QDataStream img_id_stream(data.mid(data_pos));
img_id_stream.setByteOrder(QDataStream::LittleEndian);
int img_id;
img_id_stream >> img_id;
data_pos += sizeof(int);
if (view_->aquireLock(img_id, conn)) {
// Notify all clients.
SendLockToClients(img_id);
} else {
log("Failed lock request from client. Lock already aquired.");
}
break;
}
case 0x13030006:
{
// Image release request.
QDataStream img_id_stream(data.mid(data_pos));
img_id_stream.setByteOrder(QDataStream::LittleEndian);
int img_id;
img_id_stream >> img_id;
data_pos += sizeof(int);
if (view_->releaseLock(img_id, conn)) {
// Notify all clients.
SendReleaseToClients(img_id);
} else {
log("Failed release request. Inconsistency error occured.\n");
}
break;
//.........这里部分代码省略.........
示例9: main
int main(void)
{
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 8888);
if (!socket.waitForConnected()) {
LOG_ENTRY(MyLogger::ERROR, "Unable to connect");
return -1;
}
if (!socket.waitForReadyRead()) {
LOG_ENTRY(MyLogger::ERROR, "No data received");
return -1;
}
//////////////////////
//got the HELLO
/////////////////////
QByteArray message = socket.readAll();
int size = qFromBigEndian<qint32>((const uchar*) message.data());
LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
message = message.mid(4);
if (size != 1
|| MessageCodes::getMessageType(message) != MessageCodes::HELLO) {
LOG_ENTRY(MyLogger::ERROR,
"Received wrong message: "<<MessageCodes::getMessageType(message));
return -1;
}
LOG_ENTRY(MyLogger::INFO, "Received HELLO");
QString protocolVersion = "v1.0";
message = MessageCodes::getMessageCode(MessageCodes::REQUEST_PROTOCOL)
+ protocolVersion.toUtf8();
uchar rawSize[4];
qToBigEndian((qint32) message.size(), rawSize);
message = QByteArray((char*) rawSize, 4) + message;
//////////////////////
//sent REQUEST_PROTOCOL
///////////////////////
socket.write(message);
if (!socket.waitForBytesWritten()) {
LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
return -1;
}
LOG_ENTRY(MyLogger::INFO, "REQUEST_PROTOCOL sent");
if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
LOG_ENTRY(MyLogger::ERROR, "No data received");
return -1;
}
///////////////////////
//Got ACK
//////////////////////
message = socket.readAll();
size = qFromBigEndian<qint32>((const uchar*) message.data());
LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
message = message.mid(4);
if (size != 1
|| MessageCodes::getMessageType(message) != MessageCodes::ACK) {
LOG_ENTRY(MyLogger::ERROR,
"Received wrong message: "<<MessageCodes::getMessageType(message));
return -1;
}
LOG_ENTRY(MyLogger::INFO, "Received ACK");
///////////
// Let's read the private key
//////////
AsymetricAlgorithm *algorithm = CryptographicFactory::getAsymAlgorithm(
"RSA_OAEP_SHA");
if (!algorithm) {
LOG_ENTRY(MyLogger::ERROR, "No such algorithm");
return -1;
}
QByteArray key;
QFile file("keys/Providers::Provider1.pub");
if (file.exists() && file.open(QIODevice::ReadOnly)) {
key = file.readAll();
try {
algorithm->setPublicKey(key);
LOG_ENTRY(MyLogger::INFO,
"Content of "<<file.fileName()<<" used as key file.");
} catch (AsymetricAlgorithm::AsymmetricAlgorithmException& e) {
LOG_ENTRY(MyLogger::ERROR,
"Unable to use content of file: "<<file.fileName()<<" as key: "<<e.what());
}
} else {
LOG_ENTRY(MyLogger::ERROR,
"Unable to use file: "<<file.fileName()<<" as key file");
//.........这里部分代码省略.........
示例10: onProxySocketReadyRead
void HttpProxy::onProxySocketReadyRead()
{
QTcpSocket *proxySocket = qobject_cast<QTcpSocket *>(sender());
QTcpSocket *socket = qobject_cast<QTcpSocket *>(proxySocket->parent());
socket->write(proxySocket->readAll());
}
示例11: error
void HttpProxy::onSocketReadyRead()
{
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
QTcpSocket *proxySocket = nullptr;
QByteArray reqData = socket->readAll();
int pos = reqData.indexOf("\r\n");
QByteArray reqLine = reqData.left(pos);
reqData.remove(0, pos + 2);
QList<QByteArray> entries = reqLine.split(' ');
QByteArray method = entries.value(0);
QByteArray address = entries.value(1);
QByteArray version = entries.value(2);
QString host;
quint16 port;
QString key;
if (method != "CONNECT") {
QUrl url = QUrl::fromEncoded(address);
if (!url.isValid()) {
emit error("Invalid URL: " + url.toString());
socket->disconnectFromHost();
return;
}
host = url.host();
port = url.port(80);
QString req = url.path();
if (url.hasQuery()) {
req.append('?').append(url.query());
}
reqLine = method + " " + req.toUtf8() + " " + version + "\r\n";
reqData.prepend(reqLine);
key = host + ':' + QString::number(port);
proxySocket = socket->findChild<QTcpSocket *>(key);
if (proxySocket) {
proxySocket->write(reqData);
return;//if we find an existing socket, then use it and return
}
} else {//CONNECT method
/*
* according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03
* the first line would CONNECT HOST:PORT VERSION
*/
QList<QByteArray> host_port_list = address.split(':');
host = QString(host_port_list.first());
port = host_port_list.last().toUShort();
}
proxySocket = new QTcpSocket(socket);
proxySocket->setProxy(upstreamProxy);
if (method != "CONNECT") {
proxySocket->setObjectName(key);
proxySocket->setProperty("reqData", reqData);
connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
} else {
connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
}
connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
proxySocket->connectToHost(host, port);
}
示例12: onProxySocketConnected
void HttpProxy::onProxySocketConnected()
{
QTcpSocket *proxySocket = qobject_cast<QTcpSocket *>(sender());
QByteArray reqData = proxySocket->property("reqData").toByteArray();
proxySocket->write(reqData);
}
示例13: sender
void ServerPanelRpcServer::DiscardClient() {
// Open the socket
QTcpSocket* cSocket = (QTcpSocket*) sender();
// Schedule the socket for deletion
cSocket->deleteLater();
}
示例14: getCellCorners
void getCellCorners(NDArray& cellCornerValues, const QString &hostName, quint16 port, const qint32& caseId, const quint32& gridIndex)
{
QString serverName = hostName;
quint16 serverPort = port;
QTcpSocket socket;
socket.connectToHost(serverName, serverPort);
if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
// Create command and send it:
QString command = QString("GetCellCorners %1 %2").arg(caseId).arg(gridIndex);
QByteArray cmdBytes = command.toLatin1();
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Get response. First wait for the header
while (socket.bytesAvailable() < (int)(5 * sizeof(quint64)))
{
if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
{
error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
return;
}
}
quint64 cellCountI;
quint64 cellCountJ;
quint64 cellCountK;
quint64 cellCount;
quint64 byteCount;
socketStream >> cellCount;
socketStream >> cellCountI;
socketStream >> cellCountJ;
socketStream >> cellCountK;
socketStream >> byteCount;
if (!(byteCount && cellCount))
{
error ("Could not find the requested data in ResInsight");
return;
}
dim_vector dv;
dv.resize(5);
dv(0) = cellCountI;
dv(1) = cellCountJ;
dv(2) = cellCountK;
dv(3) = 8;
dv(4) = 3;
cellCornerValues.resize(dv);
double* internalMatrixData = cellCornerValues.fortran_vec();
QStringList errorMessages;
if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), byteCount, errorMessages))
{
for (int i = 0; i < errorMessages.size(); i++)
{
error(errorMessages[i].toLatin1().data());
}
OCTAVE_QUIT;
}
return;
}
示例15: QTcpSocket
QAbstractSocket* TcpSocketCreation::operator()() const {
QTcpSocket* socket = new QTcpSocket();
socket->setSocketDescriptor(socketDescriptor);
return socket;
}