- 1. QLocalServer
- 2. QLocalSocket
В статье описывается использование QLocalServer и QLocalSocket. Пример является переработкой кода из книги Шлее «Qt 5.3. Профессиональное программирование на C++», посвящённого QTcpServer и QTcpSocket соответственно. Не смотря на то, что наименования классов похожи, и используются в одном и том же модуле, пара существенных отличий есть. Их мы рассмотрим по ходу изложения.
QLocalServer и QLocalSocket реализуют механизмы именованных каналов или сокетов домена Unix. Подробнее об этом можно почитать
здесь
и
здесь
.
Пример состоит из двух частей. В первой реализуется QLocalServer, во второй – QlocalSocket.
Сервер реализует следующий функционал: на монитор выводится виджет с текстовым полем, в котором будет отображаться информация, поступающая извне, от сокета. Сервер ожидает входящих соединений и, в случае успешного подключения, отправляет сокету сообщение об этом. Кроме того, сервер ретранслирует сокету передаваемую от сокета информацию.
В свою очередь, сокет выводит на монитор виджет с текстовым полем и кнопкой. В текстовом поле отображается информация, поступающая от сервера и служебная информация самого сокета (обнаружение подключения в начале сеанса или ошибка подключения к серверу в случае его недоступности). По нажатию кнопки сокет отправляет информацию серверу.
Рассмотрим подробно код примера.
QLocalServer
# QLocalServer.pro # Кроме модулей core gui подключаем network QT += core gui network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = QLocalServer TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS SOURCES += main.cpp mylocalserver.cpp HEADERS += mylocalserver.h// main.cpp #include "mylocalserver.h" #include <QApplication> int main(int argc, char* argv[]) { QApplication app(argc, argv); // Создаём и показываем объект класса MyLocalServer, определённого далее, // для запуска сервера с именем "MyLocalServer" MyLocalServer server("MyLocalServer"); server.show(); return app.exec(); }// mylocalserver.h #ifndef MYLOCALSERVER_H #define MYLOCALSERVER_H #include <QWidget> #include <QLocalServer> #include <QLocalSocket> #include <QTextEdit> class MyLocalServer : public QWidget { Q_OBJECT public: MyLocalServer(QString serverName, QWidget* parent = 0); ~MyLocalServer(); private: // Указатель на QLocalServer QLocalServer* localServer; // Указатель на QTextEdit, в котором будет показываться поступающая // от клиента информация QTextEdit* textEdit; // Переменная для хранения размера получаемого от клиента блока quint16 nextBlockSize; // Метод для отправки клиенту подтверждения о приёме информации void sendToClient(QLocalSocket* localSocket, const QString& string); public slots: // Слот обработки нового клиентского подключения virtual void slotNewConnection(); // Слот чтения информации от клиента void slotReadClient(); }; #endif // MYLOCALSERVER_H// mylocalserver.cpp #include "mylocalserver.h" #include <QVBoxLayout> #include <QMessageBox> #include <QLabel> #include <QTime> MyLocalServer::MyLocalServer(QString serverName, QWidget* parent) : QWidget(parent), nextBlockSize(0) // Устанавливаем nextBlockSize равным нулю { // Создаём и запускаем сервер командой listen. // Если сервер не может быть запущен, выдать сообщение об ошибке и завершить работу программы localServer = new QLocalServer(this); if(!localServer->listen(serverName)) { QMessageBox::critical(0, "Server error", "Unable to start server:" + localServer->errorString()); localServer->close(); return; } // Соединяем сигнал сервера о наличии нового подключения с обработчиком нового клиентского подключения connect(localServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); // Формируем окно для просмотра текстовых сообщений от клиента textEdit = new QTextEdit; textEdit->setReadOnly(true); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(new QLabel(serverName)); layout->addWidget(textEdit); setLayout(layout); } MyLocalServer::~MyLocalServer() { } // Слот обработки нового клиентского подключения void MyLocalServer::slotNewConnection() { // Получаем сокет, подключённый к серверу QLocalSocket* localSocket = localServer->nextPendingConnection(); // Соединяем сигнал отключения сокета с обработчиком удаления сокета connect(localSocket, SIGNAL(disconnected()), localSocket, SLOT(deleteLater())); // Соединяем сигнал сокета о готовности передачи данных с обработчиком данных connect(localSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient())); // Отправляем информацию клиенту о соединении с сервером sendToClient(localSocket, "Server response: Connected!"); } // Слот чтения информации от клиента void MyLocalServer::slotReadClient() { // Получаем QLocalSocket после срабатывания сигнала о готовности передачи данных QLocalSocket* localSocket = (QLocalSocket*)sender(); // Создаём входной поток получения данных на основе сокета QDataStream in(localSocket); // Устанавливаем версию сериализации данных потока. У клиента и сервера они должны быть одинаковыми in.setVersion(QDataStream::Qt_5_3); // Бесконечный цикл нужен для приёма блоков данных разных размеров, от двух байт и выше for(;;) { // Если размер блока равен нулю if(!nextBlockSize) { // Если размер передаваемого блока меньше двух байт, выйти из цикла if(localSocket->bytesAvailable() < (int)sizeof(quint16)) break; // Извлекаем из потока размер блока данных in >> nextBlockSize; } // Извлекаем из потока время и строку QTime time; QString string; in >> time >> string; // Преобразуем полученные данные и показываем их в виджете QString message = time.toString() + " " + "Client has sent - " + string; textEdit->append(message); nextBlockSize = 0; // Отправляем ответ клиенту sendToClient(localSocket, "Server response: received "" + string + """); } } // Метод для отправки клиенту подтверждения о приёме информации void MyLocalServer::sendToClient(QLocalSocket* localSocket, const QString& string) { // Поскольку заранее размер блока неизвестен (параметр string может быть любой длины), // вначале создаём объект array класса QByteArray QByteArray array; // На его основе создаём выходной поток QDataStream out(&array, QIODevice::WriteOnly); // Устанавливаем версию сериализации данных потока out.setVersion(QDataStream::Qt_5_3); // Записываем в поток данные для отправки. На первом месте идёт нулевой размер блока out << quint16(0) << QTime::currentTime() << string; // Перемещаем указатель на начало блока out.device()->seek(0); // Записываем двухбайтное значение действительного размера блока без учёта пересылаемого размера блока out << quint16(array.size() - sizeof(quint16)); // Отправляем получившийся блок клиенту localSocket->write(array); }QLocalSocket
# QLocalSocket.pro # Кроме модулей core gui подключаем network QT += core gui network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = QLocalSocket TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS SOURCES += main.cpp mylocalsocket.cpp HEADERS += mylocalsocket.h// main.cpp #include "mylocalsocket.h" #include <QApplication> int main(int argc, char* argv[]) { QApplication app(argc, argv); // Создаём и показываем объект класса MyLocalSocket, определённого далее, // для запуска клиента, подключаемого к серверу с именем "MyLocalServer" MyLocalSocket socket("MyLocalServer"); socket.show(); return app.exec(); }// mylocalsocket.h #ifndef MYLOCALSOCKET_H #define MYLOCALSOCKET_H #include <QWidget> #include <QLocalSocket> #include <QTextEdit> #include <QPushButton> class MyLocalSocket : public QWidget { Q_OBJECT public: MyLocalSocket(QString serverName, QWidget* parent = 0); ~MyLocalSocket(); private: // Указатель на QLocalSocket QLocalSocket* localSocket; // Указатели на элементы интерфейса QTextEdit* textEdit; QPushButton* sendRevision; // Размер принимаемого от сервера блока quint16 nextBlockSize; // Номер ревизии, отправляемый серверу // Увеличивается при каждом нажатии QPushButton int revision; private slots: // Слот чтения информации, получаемой от сервера void slotReadyRead(); // Слот обработки ошибок сокета void slotError(QLocalSocket::LocalSocketError error); // Слот передачи информации на сервер void slotSendToServer(); // Слот обработки сигнала соединения с сервером void slotConnected(); }; #endif // MYLOCALSOCKET_H// mylocalsocket.cpp #include "mylocalsocket.h" #include <QVBoxLayout> #include <QLabel> #include <QTime> #include <QMessageBox> MyLocalSocket::MyLocalSocket(QString serverName, QWidget* parent) : QWidget(parent), nextBlockSize(0), revision(0) // Устанавливаем nextBlockSize и revision равными нулю { // Инициализируем сокет localSocket = new QLocalSocket(this); // Устанавливаем соединение между сигналом ошибки сокета с обработчиком ошибок connect(localSocket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error), this, &MyLocalSocket::slotError); // Устанавливаем имя сервера, к которому сокет должен подключаться localSocket->setServerName(serverName); // Устанавливаем соединение между сигналом подключения сокета к серверу // и обработчиком сигнала connect(localSocket, SIGNAL(connected()), SLOT(slotConnected())); // Соединяем сигнал сокета о готовности приёма данных данных с обработчиком данных connect(localSocket, SIGNAL(readyRead()), SLOT(slotReadyRead())); // Инициализируем элементы интерфейса textEdit = new QTextEdit; sendRevision = new QPushButton("Send next revision"); // Соединяем нажатие кнопки с обработчиком, передающим информацию о ревизии на сервер connect(sendRevision, SIGNAL(clicked()), this, SLOT(slotSendToServer())); // Настраиваем элементы интерфейса и формируем вид окна клиента textEdit->setReadOnly(true); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(new QLabel("Sender revisions")); layout->addWidget(textEdit); layout->addWidget(sendRevision); setLayout(layout); // Подключаем сокет к серверу localSocket->connectToServer(); } MyLocalSocket::~MyLocalSocket() { } // Слот чтения информации, получаемой от сервера void MyLocalSocket::slotReadyRead() { // Всё аналогично приёму информации на стороне сервера QDataStream in(localSocket); in.setVersion(QDataStream::Qt_5_3); for(;;) { if(!nextBlockSize) { if(localSocket->bytesAvailable() < (int)sizeof(quint16)) break; } in >> nextBlockSize; if(localSocket->bytesAvailable() < nextBlockSize) break; QTime time; QString string; in >> time >> string; textEdit->append(time.toString() + " " + string); nextBlockSize = 0; } } // Слот обработки ошибок сокета void MyLocalSocket::slotError(QLocalSocket::LocalSocketError error) { QString strError = "Error: " + (error == QLocalSocket::ServerNotFoundError ? "The server was not found." : error == QLocalSocket::PeerClosedError ? "The server is closed." : error == QLocalSocket::ConnectionRefusedError ? "The connection was refused." : QString(localSocket->errorString())); textEdit->append(strError); } // Слот передачи информации на сервер void MyLocalSocket::slotSendToServer() { // Блок для передачи формируется аналогично тому, как это делается на сервере QByteArray arrayBlock; QDataStream out(&arrayBlock, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_3); ++revision; QString message = "Revision: " + QString("%1").arg(revision); out << quint16(0) << QTime::currentTime() << message; out.device()->seek(0); out << quint16(arrayBlock.size() - sizeof(quint16)); localSocket->write(arrayBlock); } // Слот обработки сигнала соединения с сервером void MyLocalSocket::slotConnected() { textEdit->append("Received the connected() signal"); }Первая особенность заключается в том, как именно подключается для QLocalSocket сигнал ошибки слота к сигналу обработки ошибок: через QOverload.
connect(localSocket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error), this, &MyLocalSocket::slotError);Вторая особенность связана с тем, что для QLocalSocket это соединение должно быть объявлено до подключения к серверу, тогда как для QTcpSocket соединение сигнала ошибки и слота обработки ошибок может быть объявлено после подключения к серверу. Подробнее об этом см. тему форума:
https://evileg.com/ru/forum/topic/965/
.
В итоге на мониторе должна быть такая картина.
Код примеров на GitHub:
QLocalServer
,
QLocalSocket
.
Самойлова Галина |
|
Статус: Новичок Группы: Участники
|
Здравствуйте. Вчера приобрели лицензию КриптоПРО CSP 5.0. Начали настраивать защищенное соединение через stunnel и столкнулись со следующей проблемой. В логах stunnel появляется следующая ошибка: 2022.01.12 11:19:36 LOG7[12192:6680]: https accepted FD=296 from 127.0.0.1:56943 2022.01.12 11:19:36 LOG3[12192:9328]: CertCreateCertificateContext failed: 2d 2022.01.12 11:19:36 LOG3[12192:9328]: Error creating credentials 2022.01.12 11:19:36 LOG3[12192:9040]: CertCreateCertificateContext failed: 2d 2022.01.12 11:19:36 LOG3[12192:9040]: Error creating credentials 2022.01.12 11:19:36 LOG3[12192:9112]: CertCreateCertificateContext failed: 2d 2022.01.12 11:19:36 LOG3[12192:9112]: Error creating credentials 2022.01.12 11:19:36 LOG3[12192:6640]: CertCreateCertificateContext failed: 2d 2022.01.12 11:19:36 LOG3[12192:6640]: Error creating credentials Файл stunnel.conf output=c:stunnelstunnel.log |
|
|
Самойлова Галина |
|
Статус: Новичок Группы: Участники
|
Пробовали сейчас настроить stunnel.conf иначе: появляется ошибка следующего характера: 2022.01.12 11:32:05 LOG5[6656:12268]: stunnel 4.18 on x86-pc-unknown 2022.01.12 11:32:48 LOG3[6656:11380]: Error creating credentials 2022.01.12 11:32:48 LOG3[6656:8896]: Error creating credentials 2022.01.12 11:32:48 LOG3[6656:11384]: Error creating credentials 2022.01.12 11:32:48 LOG3[6656:11696]: Error creating credentials
|
|
|
Андрей Русев |
|
Статус: Сотрудник Группы: Администраторы, Участники Сказал(а) «Спасибо»: 10 раз |
Здравствуйте. |
Официальная техподдержка. Официальная база знаний. |
|
|
|
Самойлова Галина |
|
Статус: Новичок Группы: Участники
|
Автор: Андрей Русев Здравствуйте. Будьте добры, подскажите. Установить на «локальный компьютер»? Верно? |
|
|
Самойлова Галина |
|
Статус: Новичок Группы: Участники
|
Автор: Андрей Русев Здравствуйте. Установили в «локальный компьютер» сертификат. Пароль на сертификате не установлен. Лог ошибки слегка изменился: |
|
|
Самойлова Галина |
|
Статус: Новичок Группы: Участники
|
Заявку можно закрыть. По новой поставили сертификат на УЦ, сертификат пользователя установили именно на компьютер, пару танцев с бубнами и всё заработало. |
|
|
Пользователи, просматривающие эту тему |
Guest |
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.
- Forum
- Qt
- Qt Programming
- emit error for QLocalSocket
-
30th August 2011, 12:30
#1
emit error for QLocalSocket
Hi,
I am implementing ‘Local fortune server’ example (from Qt 4.7.3) as a service on Windows.
What i want is that when someone paused the service, the local server should notify the error to the connected local socket (local fortune client). The error can be QLocalSocket::ServerNotFoundError.
Now, How to generate this error from server example. Please look at the following code where i want to generate this error.void FortuneServer::incomingConnection(quintptr socketDescriptor)
{
if (disabled) {
[B]// here i want to emit QLocalSocket::ServerNotFoundError [/B]
return;
}
QString fortune = fortunes.at(qrand() % fortunes.size());
FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void FortuneServer:: pause()
{
disabled = true;
}
To copy to clipboard, switch view to plain text mode
Last edited by high_flyer; 31st August 2011 at 09:53.
Reason: code tags
-
31st August 2011, 10:05
#2
Re: emit error for QLocalSocket
I am not sure what is the problem you have.
From what I understand you don’t have a problem with pausing your service, and to know that it is paused right?
If that is correct, then what is left is that you don’t know how to send a message to your client?
If so, do it just like it was a fortune cookie.
Just make a new kind of message, lets say StatusMsg, and insert the logic in the client to react to that sort of messages, analogue to the fortune cookies.
If its neither, please explain more.
-
31st August 2011, 12:14
#3
Re: emit error for QLocalSocket
I think he doesn’t want to send a message. He wants the connection from the client to be rejected. Personally I don’t think this makes sense, in such situation one could just remove the local socket.
Your biological and technological distinctiveness will be added to our own. Resistance is futile.
Please ask Qt related questions on the forum and not using private messages or visitor messages.
-
The following user says thank you to wysota for this useful post:
raj_iv (2nd September 2011)
Similar Threads
-
Replies: 9
Last Post: 30th January 2012, 16:18
-
Replies: 0
Last Post: 12th November 2010, 17:35
-
Replies: 0
Last Post: 25th March 2010, 13:04
-
Replies: 0
Last Post: 10th November 2009, 13:09
-
Replies: 1
Last Post: 11th February 2009, 21:09
Tags for this Thread
Bookmarks
Bookmarks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.
The QLocalSocket class provides a local socket.
More…
#include <qlocalsocket.h>
Public Types |
|
enum | LocalSocketError { ConnectionRefusedError = QAbstractSocket::ConnectionRefusedError, PeerClosedError = QAbstractSocket::RemoteHostClosedError, ServerNotFoundError = QAbstractSocket::HostNotFoundError, SocketAccessError = QAbstractSocket::SocketAccessError, SocketResourceError = QAbstractSocket::SocketResourceError, SocketTimeoutError = QAbstractSocket::SocketTimeoutError, DatagramTooLargeError = QAbstractSocket::DatagramTooLargeError, ConnectionError = QAbstractSocket::NetworkError, UnsupportedSocketOperationError = QAbstractSocket::UnsupportedSocketOperationError, UnknownSocketError = QAbstractSocket::UnknownSocketError } |
The LocalServerError enumeration represents the errors that can occur. More… | |
enum | LocalSocketState { UnconnectedState = QAbstractSocket::UnconnectedState, ConnectingState = QAbstractSocket::ConnectingState, ConnectedState = QAbstractSocket::ConnectedState, ClosingState = QAbstractSocket::ClosingState } |
This enum describes the different states in which a socket can be. More… | |
Public Types inherited from QIODevice | |
enum | OpenModeFlag { NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly, Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020 } |
This enum is used with open() to describe the mode in which a device is opened. More… | |
Signals |
|
void | connected () |
This signal is emitted after connectToServer() has been called and a connection has been successfully established. More… | |
void | disconnected () |
This signal is emitted when the socket has been disconnected. More… | |
void | error (QLocalSocket::LocalSocketError socketError) |
This signal is emitted after an error occurred. More… | |
void | stateChanged (QLocalSocket::LocalSocketState socketState) |
This signal is emitted whenever QLocalSocket’s state changes. More… | |
Signals inherited from QIODevice | |
void | aboutToClose () |
This signal is emitted when the device is about to close. More… | |
void | bytesWritten (qint64 bytes) |
This signal is emitted every time a payload of data has been written to the device. More… | |
void | readChannelFinished () |
This signal is emitted when the input (reading) stream is closed in this device. More… | |
void | readyRead () |
This signal is emitted once every time new data is available for reading from the device. More… | |
Signals inherited from QObject | |
void | destroyed (QObject *=0) |
This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More… | |
Public Functions |
|
void | abort () |
Aborts the current connection and resets the socket. More… | |
virtual qint64 | bytesAvailable () const |
Reimplemented Function More… | |
virtual qint64 | bytesToWrite () const |
Reimplemented Function More… | |
virtual bool | canReadLine () const |
Reimplemented Function More… | |
virtual void | close () |
Reimplemented Function More… | |
void | connectToServer (const QString &name, OpenMode openMode=ReadWrite) |
Attempts to make a connection to name. More… | |
void | disconnectFromServer () |
Attempts to close the socket. More… | |
LocalSocketError | error () const |
Returns the type of error that last occurred. More… | |
bool | flush () |
This function writes as much as possible from the internal write buffer to the socket, without blocking. More… | |
QString | fullServerName () const |
Returns the server path that the socket is connected to. More… | |
virtual bool | isSequential () const |
Reimplemented Function More… | |
bool | isValid () const |
Returns true if the socket is valid and ready for use; otherwise returns false. More… | |
QLocalSocket (QObject *parent=0) | |
Creates a new local socket. More… | |
qint64 | readBufferSize () const |
Returns the size of the internal read buffer. More… | |
QString | serverName () const |
Returns the name of the peer as specified by connectToServer(), or an empty QString if connectToServer() has not been called or it failed. More… | |
void | setReadBufferSize (qint64 size) |
Sets the size of QLocalSocket’s internal read buffer to be size bytes. More… | |
bool | setSocketDescriptor (quintptr socketDescriptor, LocalSocketState socketState=ConnectedState, OpenMode openMode=ReadWrite) |
quintptr | socketDescriptor () const |
Returns the native socket descriptor of the QLocalSocket object if this is available; otherwise returns -1. More… | |
LocalSocketState | state () const |
Returns the state of the socket. More… | |
bool | waitForBytesWritten (int msecs=30000) |
Reimplemented Function More… | |
bool | waitForConnected (int msecs=30000) |
Waits until the socket is connected, up to msecs milliseconds. More… | |
bool | waitForDisconnected (int msecs=30000) |
Waits until the socket has disconnected, up to msecs milliseconds. More… | |
bool | waitForReadyRead (int msecs=30000) |
This function blocks until data is available for reading and the QIODevice::readyRead() signal has been emitted. More… | |
~QLocalSocket () | |
Destroys the socket, closing the connection if necessary. More… | |
Public Functions inherited from QIODevice | |
virtual bool | atEnd () const |
Returns true if the current read and write position is at the end of the device (i.e. More… | |
QString | errorString () const |
Returns a human-readable description of the last device error that occurred. More… | |
bool | getChar (char *c) |
Reads one character from the device and stores it in c. More… | |
bool | isOpen () const |
Returns true if the device is open; otherwise returns false. More… | |
bool | isReadable () const |
Returns true if data can be read from the device; otherwise returns false. More… | |
bool | isTextModeEnabled () const |
Returns true if the Text flag is enabled; otherwise returns false. More… | |
bool | isWritable () const |
Returns true if data can be written to the device; otherwise returns false. More… | |
virtual bool | open (OpenMode mode) |
Opens the device and sets its OpenMode to mode. More… | |
OpenMode | openMode () const |
Returns the mode in which the device has been opened; i.e. More… | |
qint64 | peek (char *data, qint64 maxlen) |
Reads at most maxSize bytes from the device into data, without side effects (i. More… | |
QByteArray | peek (qint64 maxlen) |
Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More… | |
virtual qint64 | pos () const |
For random-access devices, this function returns the position that data is written to or read from. More… | |
bool | putChar (char c) |
Writes the character c to the device. More… | |
QIODevice () | |
Constructs a QIODevice object. More… | |
QIODevice (QObject *parent) | |
Constructs a QIODevice object with the given parent. More… | |
qint64 | read (char *data, qint64 maxlen) |
Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More… | |
QByteArray | read (qint64 maxlen) |
Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More… | |
QByteArray | readAll () |
Reads all available data from the device, and returns it as a QByteArray. More… | |
qint64 | readLine (char *data, qint64 maxlen) |
This function reads a line of ASCII characters from the device, up to a maximum of maxSize — 1 bytes, stores the characters in data, and returns the number of bytes read. More… | |
QByteArray | readLine (qint64 maxlen=0) |
Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More… | |
virtual bool | reset () |
Seeks to the start of input for random-access devices. More… | |
virtual bool | seek (qint64 pos) |
For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More… | |
void | setTextModeEnabled (bool enabled) |
If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More… | |
virtual qint64 | size () const |
For open random-access devices, this function returns the size of the device. More… | |
void | ungetChar (char c) |
Puts the character c back into the device, and decrements the current position unless the position is 0. More… | |
qint64 | write (const char *data, qint64 len) |
Writes at most maxSize bytes of data from data to the device. More… | |
qint64 | write (const char *data) |
Writes data from a zero-terminated string of 8-bit characters to the device. More… | |
qint64 | write (const QByteArray &data) |
Writes the content of byteArray to the device. More… | |
virtual | ~QIODevice () |
The destructor is virtual, and QIODevice is an abstract base class. More… | |
Public Functions inherited from QObject | |
bool | blockSignals (bool b) |
If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More… | |
const QObjectList & | children () const |
Returns a list of child objects. More… | |
bool | connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const |
bool | disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0) |
bool | disconnect (const QObject *receiver, const char *member=0) |
void | dumpObjectInfo () |
Dumps information about signal connections, etc. More… | |
void | dumpObjectTree () |
Dumps a tree of children to the debug output. More… | |
QList< QByteArray > | dynamicPropertyNames () const |
Returns the names of all properties that were dynamically added to the object using setProperty(). More… | |
virtual bool | event (QEvent *) |
This virtual function receives events to an object and should return true if the event e was recognized and processed. More… | |
virtual bool | eventFilter (QObject *, QEvent *) |
Filters events if this object has been installed as an event filter for the watched object. More… | |
template<typename T > | |
T | findChild (const QString &aName=QString()) const |
Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More… | |
template<typename T > | |
QList< T > | findChildren (const QString &aName=QString()) const |
Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More… | |
template<typename T > | |
QList< T > | findChildren (const QRegExp &re) const |
bool | inherits (const char *classname) const |
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More… | |
void | installEventFilter (QObject *) |
Installs an event filter filterObj on this object. More… | |
bool | isWidgetType () const |
Returns true if the object is a widget; otherwise returns false. More… | |
void | killTimer (int id) |
Kills the timer with timer identifier, id. More… | |
virtual const QMetaObject * | metaObject () const |
Returns a pointer to the meta-object of this object. More… | |
void | moveToThread (QThread *thread) |
Changes the thread affinity for this object and its children. More… | |
QString | objectName () const |
QObject * | parent () const |
Returns a pointer to the parent object. More… | |
QVariant | property (const char *name) const |
Returns the value of the object’s name property. More… | |
Q_INVOKABLE | QObject (QObject *parent=0) |
Constructs an object with parent object parent. More… | |
void | removeEventFilter (QObject *) |
Removes an event filter object obj from this object. More… | |
void | setObjectName (const QString &name) |
void | setParent (QObject *) |
Makes the object a child of parent. More… | |
bool | setProperty (const char *name, const QVariant &value) |
Sets the value of the object’s name property to value. More… | |
void | setUserData (uint id, QObjectUserData *data) |
bool | signalsBlocked () const |
Returns true if signals are blocked; otherwise returns false. More… | |
int | startTimer (int interval) |
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More… | |
QThread * | thread () const |
Returns the thread in which the object lives. More… | |
QObjectUserData * | userData (uint id) const |
virtual | ~QObject () |
Destroys the object, deleting all its child objects. More… | |
Protected Functions |
|
virtual qint64 | readData (char *, qint64) |
Reimplemented Function More… | |
virtual qint64 | writeData (const char *, qint64) |
Reimplemented Function More… | |
Protected Functions inherited from QIODevice | |
QIODevice (QIODevicePrivate &dd, QObject *parent=0) | |
virtual qint64 | readLineData (char *data, qint64 maxlen) |
Reads up to maxSize characters into data and returns the number of characters read. More… | |
void | setErrorString (const QString &errorString) |
Sets the human readable description of the last device error that occurred to str. More… | |
void | setOpenMode (OpenMode openMode) |
Sets the OpenMode of the device to openMode. More… | |
Protected Functions inherited from QObject | |
virtual void | childEvent (QChildEvent *) |
This event handler can be reimplemented in a subclass to receive child events. More… | |
virtual void | connectNotify (const char *signal) |
This virtual function is called when something has been connected to signal in this object. More… | |
virtual void | customEvent (QEvent *) |
This event handler can be reimplemented in a subclass to receive custom events. More… | |
virtual void | disconnectNotify (const char *signal) |
This virtual function is called when something has been disconnected from signal in this object. More… | |
QObject (QObjectPrivate &dd, QObject *parent=0) | |
int | receivers (const char *signal) const |
Returns the number of receivers connected to the signal. More… | |
QObject * | sender () const |
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More… | |
int | senderSignalIndex () const |
virtual void | timerEvent (QTimerEvent *) |
This event handler can be reimplemented in a subclass to receive timer events for the object. More… | |
Additional Inherited Members |
|
Public Slots inherited from QObject | |
void | deleteLater () |
Schedules this object for deletion. More… | |
Static Public Functions inherited from QObject | |
static bool | connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection) |
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More… | |
static bool | connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection) |
static bool | disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member) |
Disconnects signal in object sender from method in object receiver. More… | |
static bool | disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member) |
static uint | registerUserData () |
static QString | tr (const char *sourceText, const char *comment=0, int n=-1) |
static QString | trUtf8 (const char *sourceText, const char *comment=0, int n=-1) |
Static Public Variables inherited from QObject | |
static const QMetaObject | staticMetaObject |
This variable stores the meta-object for the class. More… | |
Protected Variables inherited from QObject | |
QScopedPointer< QObjectData > | d_ptr |
Static Protected Variables inherited from QObject | |
static const QMetaObject | staticQtMetaObject |
Related Functions inherited from QObject | |
T | qFindChildqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QString &name)() |
QList< T > | qFindChildrenqFindChildren (const QObject *obj, const QRegExp ®Exp)() |
T * | qobject_cast (QObject *object) |
QObjectList | |
void * | qt_find_obj_child (QObject *parent, const char *type, const QString &name) |
Returns a pointer to the object named name that inherits type and with a given parent. More… | |
The QLocalSocket class provides a local socket.
- Since
- 4.4
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs, socketError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
Although QLocalSocket is designed for use with an event loop, it’s possible to use it without one. In that case, you must use waitForConnected(), waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected() which blocks until the operation is complete or the timeout expires.
Note that this feature is not supported on versions of Windows earlier than Windows XP.
- See also
- QLocalServer
Definition at line 58 of file qlocalsocket.h.
◆ LocalSocketError
The LocalServerError enumeration represents the errors that can occur.
The most recent error can be retrieved through a call to QLocalSocket::error() .
- ConnectionRefusedError The connection was refused by the peer (or timed out).
- PeerClosedError The remote socket closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.
- ServerNotFoundError The local socket name was not found.
- SocketAccessError The socket operation failed because the application lacked the required privileges.
- SocketResourceError The local system ran out of resources (e.g., too many sockets).
- SocketTimeoutError The socket operation timed out.
- DatagramTooLargeError The datagram was larger than the operating system’s limit (which can be as low as 8192 bytes).
- ConnectionError An error occurred with the connection.
- UnsupportedSocketOperationError The requested socket operation is not supported by the local operating system.
- UnknownSocketError An unidentified error occurred.
Enumerator | |
---|---|
ConnectionRefusedError | |
PeerClosedError | |
ServerNotFoundError | |
SocketAccessError | |
SocketResourceError | |
SocketTimeoutError | |
DatagramTooLargeError | |
ConnectionError | |
UnsupportedSocketOperationError | |
UnknownSocketError |
Definition at line 64 of file qlocalsocket.h.
◆ LocalSocketState
This enum describes the different states in which a socket can be.
- See also
- QLocalSocket::state()
- UnconnectedState The socket is not connected.
- ConnectingState The socket has started establishing a connection.
- ConnectedState A connection is established.
- ClosingState The socket is about to close (data may still be waiting to be written).
Enumerator | |
---|---|
UnconnectedState | |
ConnectingState | |
ConnectedState | |
ClosingState |
Definition at line 78 of file qlocalsocket.h.
QLocalSocket::QLocalSocket | ( | QObject * | parent = 0 |
) |
Creates a new local socket.
The parent argument is passed to QObject’s constructor.
Definition at line 390 of file qlocalsocket.cpp.
392 {
394 d->init();
395 }
The QLocalSocket class provides a local socket.
QIODevice()
Constructs a QIODevice object.
◆ ~QLocalSocket()
QLocalSocket::~QLocalSocket | ( | ) |
Destroys the socket, closing the connection if necessary.
Definition at line 400 of file qlocalsocket.cpp.
401 {
403 #if !defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
405 d->unixSocket.setParent(0);
406 #endif
407 }
virtual void close()
Reimplemented Function
The QLocalSocket class provides a local socket.
◆ abort()
void QLocalSocket::abort | ( | ) |
◆ bytesAvailable()
|
virtual |
◆ bytesToWrite()
|
virtual |
◆ canReadLine()
|
virtual |
Reimplemented Function
Reimplemented from QIODevice.
Definition at line 326 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_pipeClosed().
327 {
330 }
The QLocalSocket class provides a local socket.
virtual bool canReadLine() const
Returns true if a complete line of data can be read from the device; otherwise returns false…
◆ close()
|
virtual |
◆ connected
|
signal |
◆ connectToServer()
void QLocalSocket::connectToServer | ( | const QString & | name, |
OpenMode | openMode = ReadWrite |
||
) |
Attempts to make a connection to name.
The socket is opened in the given openMode and first enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QLocalSocket enters ConnectedState and emits connected().
At any point, the socket can emit error() to signal that an error occurred.
See also state(), serverName(), and waitForConnected().
Definition at line 214 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::destroyPipeHandles().
215 {
219 return;
220
221 d->errorString.clear();
224
228 return;
229 }
230
231 d->serverName = name;
234 d->fullServerName = name;
235 else
236 d->fullServerName = prefix + name;
237
239 bool ok;
241 if (!ok) {
244 return;
245 }
248 }
QVariant value(const QString &key, const QVariant &defaultValue=QVariant()) const
Returns the value for setting key.
The QSettings class provides persistent platform-independent application settings.
bool startsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string starts with s; otherwise returns false.
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
LocalSocketState state() const
Returns the state of the socket.
The QLocalSocket class provides a local socket.
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal…
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
uint toUInt(bool *ok=0) const
Returns the variant as an unsigned int if the variant has type() UInt , Bool , ByteArray …
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
void stateChanged(QLocalSocket::LocalSocketState socketState)
This signal is emitted whenever QLocalSocket's state changes.
◆ disconnected
|
signal |
◆ disconnectFromServer()
void QLocalSocket::disconnectFromServer | ( | ) |
Attempts to close the socket.
If there is pending data waiting to be written, QLocalSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnectedFromServer() signal.
- See also
- connectToServer()
Definition at line 353 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_pipeClosed().
354 {
356 d->tcpSocket->disconnectFromHost();
357 }
The QLocalSocket class provides a local socket.
◆ error() [1/2]
Returns the type of error that last occurred.
- See also
- state(), errorString()
Definition at line 359 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_pipeClosed().
360 {
362 switch (d->tcpSocket->error()) {
383 default:
384 #if defined QLOCALSOCKET_DEBUG
385 qWarning() << «QLocalSocket error not handled:» << d->tcpSocket->error();
386 #endif
387 break;
388 }
390 }
The QLocalSocket class provides a local socket.
Q_CORE_EXPORT void qWarning(const char *,…)
◆ error [2/2]
◆ flush()
bool QLocalSocket::flush | ( | ) |
This function writes as much as possible from the internal write buffer to the socket, without blocking.
If any data was written, this function returns true; otherwise false is returned.
Call this function if you need QLocalSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, because QLocalSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.
- See also
- write(), waitForBytesWritten()
Definition at line 347 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_pipeClosed().
348 {
350 return d->tcpSocket->flush();
351 }
The QLocalSocket class provides a local socket.
◆ fullServerName()
QString QLocalSocket::fullServerName | ( | ) | const |
Returns the server path that the socket is connected to.
- Note
- The return value of this function is platform specific.
- See also
- connectToServer(), serverName()
Definition at line 429 of file qlocalsocket.cpp.
430 {
432 return d->fullServerName;
433 }
The QLocalSocket class provides a local socket.
◆ isSequential()
|
virtual |
◆ isValid()
bool QLocalSocket::isValid | ( | ) | const |
◆ readBufferSize()
qint64 QLocalSocket::readBufferSize | ( | ) | const |
◆ readData()
|
protectedvirtual |
◆ serverName()
QString QLocalSocket::serverName | ( | ) | const |
◆ setReadBufferSize()
void QLocalSocket::setReadBufferSize | ( | qint64 | size | ) |
Sets the size of QLocalSocket’s internal read buffer to be size bytes.
If the buffer size is limited to a certain size, QLocalSocket won’t buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.
This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.
- See also
- readBufferSize(), read()
Definition at line 404 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_emitReadyRead().
405 {
407 d->tcpSocket->setReadBufferSize(size);
408 }
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
The QLocalSocket class provides a local socket.
◆ setSocketDescriptor()
Definition at line 250 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_pipeClosed(), and QLocalServer::incomingConnection().
252 {
255 switch (socketState) {
258 break;
261 break;
264 break;
267 break;
268 }
270 d->state = socketState;
271
272
274 if (localServer) {
278 d->setSocket( static_cast<QLocalUnixSocket*>(childTcpSocket) );
279 return true;
280 }
281 }
282 }
283
284
285
288 }
quintptr socketDescriptor() const
Returns the native socket descriptor of the QLocalSocket object if this is available; otherwise retur…
int socketDescriptor() const
Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise re…
T * qobject_cast(QObject *object)
The QObject class is the base class of all Qt objects.
The QLocalSocket class provides a local socket.
SocketState
This enum describes the different states in which a socket can be.
The QLocalServer class provides a local socket based server.
The QTcpSocket class provides a TCP socket.
OpenMode openMode() const
Returns the mode in which the device has been opened; i.e.
QObject * parent() const
Returns a pointer to the parent object.
const QObjectList & children() const
Returns a list of child objects.
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
◆ socketDescriptor()
quintptr QLocalSocket::socketDescriptor | ( | ) | const |
◆ state()
Returns the state of the socket.
- See also
- error()
Definition at line 440 of file qlocalsocket.cpp.
441 {
443 return d->state;
444 }
The QLocalSocket class provides a local socket.
◆ stateChanged
This signal is emitted whenever QLocalSocket’s state changes.
The socketState parameter is the new state.
QLocalSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().
- See also
- state(), {Creating Custom Qt Types}
◆ waitForBytesWritten()
|
virtual |
◆ waitForConnected()
bool QLocalSocket::waitForConnected | ( | int | msecs = 30000 |
) |
Waits until the socket is connected, up to msecs milliseconds.
If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.
The following example waits up to one second for a connection to be established:
socket->connectToServer(«market»);
if (socket->waitForConnected(1000))
If msecs is -1, this function will not time out.
- See also
- connectToServer(), connected()
Definition at line 410 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_emitReadyRead().
411 {
415
416 return d->tcpSocket->waitForConnected(msec);
417 }
LocalSocketState state() const
Returns the state of the socket.
The QLocalSocket class provides a local socket.
◆ waitForDisconnected()
bool QLocalSocket::waitForDisconnected | ( | int | msecs = 30000 |
) |
Waits until the socket has disconnected, up to msecs milliseconds.
If the connection has been disconnected, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.
The following example waits up to one second for a connection to be closed:
socket->disconnectFromServer();
if (socket->waitForDisconnected(1000))
If msecs is -1, this function will not time out.
- See also
- disconnectFromServer(), close()
Definition at line 419 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_emitReadyRead().
420 {
423 qWarning() << «QLocalSocket::waitForDisconnected() is not allowed in UnconnectedState»;
424 return false;
425 }
426 return (d->tcpSocket->waitForDisconnected(msecs));
427 }
LocalSocketState state() const
Returns the state of the socket.
The QLocalSocket class provides a local socket.
Q_CORE_EXPORT void qWarning(const char *,…)
◆ waitForReadyRead()
|
virtual |
This function blocks until data is available for reading and the QIODevice::readyRead() signal has been emitted.
The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.
The function returns true if data is available for reading; otherwise it returns false (if an error occurred or the operation timed out).
- See also
- waitForBytesWritten()
Reimplemented from QIODevice.
Definition at line 429 of file qlocalsocket_tcp.cpp.
Referenced by QLocalSocketPrivate::_q_emitReadyRead().
430 {
433 return false;
434 return (d->tcpSocket->waitForReadyRead(msecs));
435 }
LocalSocketState state() const
Returns the state of the socket.
The QLocalSocket class provides a local socket.
◆ writeData()
|
protectedvirtual |
The documentation for this class was generated from the following files:
- /src/network/socket/qlocalsocket.h
- /src/network/socket/qlocalsocket.cpp
- /src/network/socket/qlocalsocket_tcp.cpp
- /src/network/socket/qlocalsocket_unix.cpp
- /src/network/socket/qlocalsocket_win.cpp
Hi there, I’m creating a firejail profile for a socket browser (see) https://bbs.archlinux.org/viewtopic.php?id=263121
installed firejail version : firejail 0.9.64.2-1
Now, the profile is still basic but it works until I open a page..
The profile:
# Firejail profile for weaver
# Description: socket controlled web browser from: https://code.jessemcclure.org/weaver
# This file is overwritten after every install/update
# Persistent global definitions
#include globals.local
# Persistent local customizations
include weaver.local
# weaver used dirs.
noblacklist ${HOME}/.cache/weaver
noblacklist ${HOME}/.config/weaver
noblacklist ${HOME}/.local/weaver
# weaver socket
noblacklist /run/user/1000/weaver
# if dirs. are not created, create and whitelist them
mkdir ${HOME}/.cache/weaver
whitelist ${HOME}/.cache/weaver
mkdir ${HOME}/.config/weaver
whitelist ${HOME}/.config/weaver
blacklist /tmp/.X11-unix
blacklist ${RUNUSER}/wayland-*
include /etc/firejail/whitelist-common.inc
#include /etc/firejail/default.profile
whitelist /usr/share/doc
include whitelist-usr-share-common.inc
caps.drop all
netfilter
nonewprivs
noroot
protocol unix,inet,inet6,netlink
seccomp
The result is what you want to see, here’s the command without firejail;
$weaver
Listening on socket "/run/user/1000/weaver"
The program running the profile.I still need to work around ‘protocol’ if I add it to the profile it fails( at the moment)
$firejail --protocol=unix,inet,inet6,netlink --profile=~/.config/firejail/weaver.profile weaver
Reading profile /home/mark/.config/firejail/weaver.profile
Reading profile /etc/firejail/whitelist-common.inc
Reading profile /etc/firejail/default.profile
Reading profile /etc/firejail/disable-common.inc
Reading profile /etc/firejail/disable-passwdmgr.inc
Reading profile /etc/firejail/disable-programs.inc
Warning: two protocol lists are present, "unix,inet,inet6,netlink" will be installed
Reading profile /etc/firejail/whitelist-usr-share-common.inc
Reading profile /etc/firejail/whitelist-runuser-common.inc
Parent pid 1011353, child pid 1011354
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: /sbin directory link was not blacklisted
Warning: /usr/sbin directory link was not blacklisted
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Child process initialized in 59.02 ms
Listening on socket "/run/user/1000/weaver"
If actually try to run a page I get the following error message:
I looked at about all existing profiles in ‘etc/firejail’ and tried a lot, but I can’t find a solution.
This is the message:
$weaver open-window https://bbs.archlinux.org
Error: QLocalSocket::ConnectionRefusedError
Appreciate your input, thanks..
edit: updated firejail , tested new version with the above profile( same result ) and added version installed (above)
edit2: Oh my, simply commenting ‘include whitelist-runuser-common.inc’ solved my issue, page is opening.
I updated the profile above into the working one, it’s just a start and nowhere finished..
—————————
edit3: I pasted the updated profile above, the ‘protocol’ warning is solved it was inherited..
You can now run it with
firejail --profile=weaver.profile weaver
The actual (new) output from the terminal
$firejail --profile=~/.config/firejail/weaver.profile weaver
Reading profile /home/mark/.config/firejail/weaver.profile
Reading profile /etc/firejail/whitelist-common.inc
Reading profile /etc/firejail/whitelist-usr-share-common.inc
Parent pid 82884, child pid 82885
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Warning: cleaning all supplementary groups
Child process initialized in 31.92 ms
Listening on socket "/run/user/1000/weaver"
If you have more hardening suggestions please share, thanks.
Last edited by qinohe (2021-02-03 20:38:31)
Класс QLocalSocket предоставляет локальный сокет. Более…
Header: | #include <QLocalSocket> |
CMake: | find_package(Qt6 COMPONENTS Network REQUIRED) target_link_libraries(mytarget PRIVATE Qt6::Network) |
qmake: | QT +=сеть |
Inherits: | QIODevice |
- Список всех членов,включая унаследованных членов
Public Types
enum | LocalSocketError { ConnectionRefusedError, PeerClosedError, ServerNotFoundError, SocketAccessError, SocketResourceError, …, UnknownSocketError } |
enum | LocalSocketState { UnconnectedState , ConnectingState, ConnectedState, ClosingState} |
enum | SocketOption { NoOptions, AbstractNamespaceOption } |
flags | SocketOptions |
Properties
- сокетоптионс : сокетоптионс
Public Functions
Реализованные общественные функции
Signals
Реализованные защищенные функции
virtual qint64 | readData(char *data, qint64c) override |
virtual qint64 | skipData(qint64maxSize) override |
virtual qint64 | writeData(const char *data, qint64c) override |
Detailed Description
В Windows это именованный канал,а в Unix-локальный доменный сокет.
Если возникает ошибка, error () возвращает тип ошибки, а errorString () может быть вызвана для получения удобочитаемого описания того, что произошло.
Хотя QLocalSocket предназначен для использования с циклом обработки событий, его можно использовать и без него. В этом случае вы должны использовать waitForConnected (), waitForReadyRead (), waitForBytesWritten () и waitForDisconnected (), которые блокируются до завершения операции или истечения времени ожидания.
Смотрите также QLocalServer .
Тип члена Документация
enum QLocalSocket::LocalSocketError
Перечисление LocalServerError представляет возможные ошибки. Самую последнюю ошибку можно получить с помощью вызова QLocalSocket::error ().
Constant | Value | Description |
---|---|---|
QLocalSocket::ConnectionRefusedError |
QAbstractSocket::ConnectionRefusedError |
Соединение было отвергнуто коллегой (или установлено по таймеру). |
QLocalSocket::PeerClosedError |
QAbstractSocket::RemoteHostClosedError |
Выносная розетка закрыла соединение.Обратите внимание,что клиентское гнездо (т.е.это гнездо)будет закрыто после отправки уведомления об удаленном закрытии. |
QLocalSocket::ServerNotFoundError |
QAbstractSocket::HostNotFoundError |
Местное название розетки не найдено. |
QLocalSocket::SocketAccessError |
QAbstractSocket::SocketAccessError |
Операция сокета завершилась неудачей,потому что приложению не хватало требуемых привилегий. |
QLocalSocket::SocketResourceError |
QAbstractSocket::SocketResourceError |
В локальной системе закончились ресурсы (например,слишком много розеток). |
QLocalSocket::SocketTimeoutError |
QAbstractSocket::SocketTimeoutError |
Срок срабатывания розетки истек. |
QLocalSocket::DatagramTooLargeError |
QAbstractSocket::DatagramTooLargeError |
Датаграмма была больше предела операционной системы (который может быть до 8192 байт). |
QLocalSocket::ConnectionError |
QAbstractSocket::NetworkError |
Произошла ошибка при соединении. |
QLocalSocket::UnsupportedSocketOperationError |
QAbstractSocket::UnsupportedSocketOperationError |
Запрошенная операция розетки не поддерживается локальной операционной системой. |
QLocalSocket::OperationError |
QAbstractSocket::OperationError |
Операция была предпринята в то время,когда розетка находилась в состоянии,не позволяющем ее проведение. |
QLocalSocket::UnknownSocketError |
QAbstractSocket::UnknownSocketError |
Произошла неопознанная ошибка. |
enum QLocalSocket::LocalSocketState
Это перечисление описывает различные состояния,в которых может находиться розетка.
Constant | Value | Description |
---|---|---|
QLocalSocket::UnconnectedState |
QAbstractSocket::UnconnectedState |
Розетка не подключена. |
QLocalSocket::ConnectingState |
QAbstractSocket::ConnectingState |
Розетка начала устанавливать соединение. |
QLocalSocket::ConnectedState |
QAbstractSocket::ConnectedState |
Соединение установлено. |
QLocalSocket::ClosingState |
QAbstractSocket::ClosingState |
Сокет вот-вот закроется (данные могут еще ждать записи). |
См. также QLocalSocket::state ().
[since 6.2]
enum QLocalSocket::SocketOptionflags QLocalSocket::SocketOptions
Это перечисление описывает возможные опции,которые могут быть использованы для подключения к серверу.В настоящее время в Linux и Android он используется для указания подключения к серверу,прослушивающему сокет,привязанный к абстрактному адресу.
Constant | Value | Description |
---|---|---|
QLocalSocket::NoOptions |
0x00 |
Никаких опций не было установлено. |
QLocalSocket::AbstractNamespaceOption |
0x01 |
Сокет будет пытаться подключиться к абстрактному адресу.Этот флаг специфичен для Linux и Android.На других платформах игнорируется. |
Это перечисление было введено или изменено в Qt 6.2.
Тип SocketOptions — это определение типа для QFlags <SocketOption>. Он хранит комбинацию значений SocketOption по ИЛИ.
См. также параметры сокета .
Property Documentation
[bindable, since 6.2]
socketOptions : SocketOptions
Примечание. Это свойство поддерживает привязки QProperty .
Это свойство содержит параметры сокета.
Параметры должны быть установлены, пока сокет находится в состоянии UnconnectedState .
Это свойство было введено в Qt 6.2.
См. Также connectToServer ().
Документация по функциям члена
QLocalSocket::QLocalSocket(QObject *parent= nullptr)
Создает новую местную розетку.parentаргумент передается конструктору QObject .
[signal]
void QLocalSocket::connected()
Этот сигнал излучается после вызова connectToServer () и успешного установления соединения.
Смотрите также connectToServer () и отключения ().
[signal]
void QLocalSocket::disconnected()
Этот сигнал подается при отсоединении гнезда.
См. также connectToServer (), disconnectFromServer (), abort () иconnected ( ).
[signal, since 5.15]
версии 5.15] void QLocalSocket :: errorOccurred ( QLocalSocket :: LocalSocketError socketError)
Этот сигнал подается после возникновения ошибки.socketErrorПараметр описывает тип возникшей ошибки.
QLocalSocket::LocalSocketError не является зарегистрированным метатипом, поэтому для подключений в очереди вам придется зарегистрировать его с помощью Q_DECLARE_METATYPE () и qRegisterMetaType ().
Эта функция была введена в Qt 5.15.
См. также error (), errorString () и Создание пользовательских типов Qt .
[signal]
void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)
Этот сигнал испускается всякий раз, когда изменяется состояние QLocalSocket . ВsocketStateпараметр-новое состояние.
QLocalSocket::SocketState не является зарегистрированным метатипом, поэтому для подключений в очереди вам придется зарегистрировать его с помощью Q_DECLARE_METATYPE () и qRegisterMetaType ().
См. также state () и Создание пользовательских типов Qt .
[virtual]
QLocalSocket::~QLocalSocket()
Разрушает розетку,при необходимости замыкает соединение.
void QLocalSocket::abort()
Прерывает текущее соединение и сбрасывает сокет. В отличие от disconnectFromServer (), эта функция сразу же закрывает сокет, очищая все ожидающие данные в буфере записи.
См. также разъединение от сервера () и закрытие ().
[override virtual]
qint64 QLocalSocket::bytesAvailable() const
Реализует: QIODevice::bytesAvailable() const .
[override virtual]
qint64 QLocalSocket::bytesToWrite() const
Реализует: QIODevice::bytesToWrite() const .
[override virtual]
bool QLocalSocket::canReadLine() const
Реализует: QIODevice::canReadLine() const .
[override virtual]
void QLocalSocket::close()
Reimplements: QIODevice::close().
[since 5.1]
версии 5.1] void QLocalSocket :: connectToServer ( QIODeviceBase :: OpenMode openMode= ReadWrite)
Попытки установить соединение с serverName (). setServerName () необходимо вызывать до того, как вы откроете соединение. В качестве альтернативы вы можете использовать connectToServer(const QString &name, OpenMode openMode);
Гнездо открывается в данномopenModeи сначала входит в ConnectingState . Если соединение установлено, QLocalSocket входит в ConnectedState и излучает connected ().
После вызова этой функции сокет может выдать errorOccurred (), чтобы сообщить об ошибке.
Эта функция была введена в Qt 5.1.
См. также state (), serverName () и waitForConnected ().
void QLocalSocket::connectToServer(const QString &name, QIODeviceBase::OpenMode openMode= ReadWrite)
Это перегруженная функция.
Установить серверnameи попытки установить с ним связь.
Гнездо открывается в данномopenModeи сначала входит в ConnectingState . Если соединение установлено, QLocalSocket входит в ConnectedState и излучает connected ().
После вызова этой функции сокет может выдать errorOccurred (), чтобы сообщить об ошибке.
См. также state (), serverName () и waitForConnected ().
© The Qt Company Ltd
Licensed under the GNU Free Documentation License, Version 1.3.
https://doc.qt.io/qt-6.2/qlocalsocket.html
Qt
6.2
-
QLocale::toString(дата, константа и формат) константа
Возвращает локализованное строковое представление заданного формата даты.
-
QLocalServer Class
Класс QLocalServer обеспечивает работу с сокетами Этот класс позволяет принимать входящие локальные сокетные соединения.
-
void QLocalSocket::disconnectFromServer()
Попытки закрыть сокет.
-
QLockFile Class
Класс QLockFile обеспечивает блокировку между процессами,используя Файл блокировки может использоваться для предотвращения одновременного доступа нескольких процессов к одному и тому же файлу.
Я реализую пример «Локального сервера удачи» (из Qt 4.7.3) в качестве службы в Windows. Я хочу, чтобы, когда кто-то приостановил службу, локальный сервер должен уведомлять об ошибке подключенный локальный сокет (локальный клиент удачи). Ошибка может быть QLocalSocket :: ServerNotFoundError. Теперь, как сгенерировать эту ошибку на примере сервера. Посмотрите на следующий код, в котором я хочу сгенерировать эту ошибку.
void FortuneServer::incomingConnection(quintptr socketDescriptor)
{
if (disabled) {
**// here i want to emit QLocalSocket::ServerNotFoundError**
return;
}
QString fortune = fortunes.at(qrand() % fortunes.size());
FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void FortuneServer:: pause()
{
disabled = true;
}
2 ответы
Если вы хотите, чтобы ваш сервер уведомлял ваших клиентов, я думаю, вам следует создать и отправить собственное сообщение, например:
QString fortune = "Server down";
Но это произойдет, когда ваш сервер получит входящее сообщение.
или вы можете выключить сервер с помощью QTcpServer :: close () метод
void FortuneServer:: pause()
{
this.close();
}
ваше клиентское приложение потеряет соединение, и вы сможете получить в нем нужный сигнал с помощью этого:
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(displayError(QAbstractSocket::SocketError)));
ответ дан 30 авг.
Вы не можете испускать QLocalSocket::ServerNotFoundError
, потому что это не сигнал. Вы должны определить свой собственный сигнал и испустить его вместо этого (вы можете передавать значения в сигналах). Вы также должны реализовать слот и подключить к нему сигнал. Узнать больше о сигналы и слоты.
ответ дан 30 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
qt
qt4
qlocalsocket
or задайте свой вопрос.