QBluetoothServer Class
La clase QBluetoothServer utiliza el protocolo RFCOMM o L2cap para comunicarse con un dispositivo Bluetooth. Más información...
| Encabezado: | #include <QBluetoothServer> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Bluetooth) target_link_libraries(mytarget PRIVATE Qt6::Bluetooth) |
| qmake: | QT += bluetooth |
| Heredado de: | QObject |
Tipos públicos
| enum | Error { NoError, UnknownError, PoweredOffError, InputOutputError, ServiceAlreadyRegisteredError, …, MissingPermissionsError } |
Funciones públicas
| QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr) | |
| virtual | ~QBluetoothServer() |
| void | close() |
| QBluetoothServer::Error | error() const |
| bool | hasPendingConnections() const |
| bool | isListening() const |
| bool | listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0) |
| QBluetoothServiceInfo | listen(const QBluetoothUuid &uuid, const QString &serviceName = QString()) |
| int | maxPendingConnections() const |
| QBluetoothSocket * | nextPendingConnection() |
| QBluetooth::SecurityFlags | securityFlags() const |
| QBluetoothAddress | serverAddress() const |
| quint16 | serverPort() const |
| QBluetoothServiceInfo::Protocol | serverType() const |
| void | setMaxPendingConnections(int numConnections) |
| void | setSecurityFlags(QBluetooth::SecurityFlags security) |
Señales
(since 6.2) void | errorOccurred(QBluetoothServer::Error error) |
| void | newConnection() |
Descripción detallada
QBluetoothServer se utiliza para implementar servicios Bluetooth a través de RFCOMM o L2cap.
Comienza a escuchar conexiones entrantes con ` listen()`. Espera a que se emita la señal ` newConnection()` cuando se establezca una nueva conexión y llama a ` nextPendingConnection()` para obtener un ` QBluetoothSocket ` para la nueva conexión.
Para que otros dispositivos puedan encontrar tu servicio, crea un « QBluetoothServiceInfo » con los atributos correspondientes a tu servicio y regístralo mediante « QBluetoothServiceInfo::registerService()». Llama a « serverPort()» para obtener el número de canal que se está utilizando.
Si una plataforma no es compatible con QBluetoothServiceInfo::Protocol, listen() devolverá false. Por ejemplo, Android y WinRT solo admiten RFCOMM.
En iOS, esta clase no se puede utilizar porque la plataforma no expone una API que permita el acceso a las funciones relacionadas con QBluetoothServer.
Véase también QBluetoothServiceInfo y QBluetoothSocket.
Documentación sobre los tipos de miembros
enum QBluetoothServer::Error
Esta enumeración describe los tipos de error del servidor Bluetooth.
| Constante | Valor | Descripción |
|---|---|---|
QBluetoothServer::NoError | 0 | Sin error. |
QBluetoothServer::UnknownError | 1 | Se ha producido un error desconocido. |
QBluetoothServer::PoweredOffError | 2 | El adaptador Bluetooth está apagado. |
QBluetoothServer::InputOutputError | 3 | Se ha producido un error de entrada/salida. |
QBluetoothServer::ServiceAlreadyRegisteredError | 4 | El servicio o el puerto ya estaban registrados |
QBluetoothServer::UnsupportedProtocolError | 5 | Protocol no es compatible con esta plataforma. |
QBluetoothServer::MissingPermissionsError (since Qt 6.4) | 6 | El sistema operativo solicita permisos que el usuario no ha concedido. |
Documentación de funciones de miembro
[explicit] QBluetoothServer::QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr)
Crea un servidor Bluetooth con parent y serverType.
[virtual noexcept] QBluetoothServer::~QBluetoothServer()
Elimina el servidor Bluetooth.
void QBluetoothServer::close()
Cierra y restablece el socket de escucha. Cualquier conexión ya establecida QBluetoothSocket seguirá funcionando y deberá cerrarse por separado closed.
QBluetoothServer::Error QBluetoothServer::error() const
Devuelve el último error de la función « QBluetoothServer ».
[signal, since 6.2] void QBluetoothServer::errorOccurred(QBluetoothServer::Error error)
Esta señal se emite cuando se produce un « error ».
Esta función se introdujo en Qt 6.2.
Véase también ` error()` y ` QBluetoothServer::Error`.
bool QBluetoothServer::hasPendingConnections() const
Devuelve «true» si hay una conexión pendiente; en caso contrario, devuelve «false».
bool QBluetoothServer::isListening() const
Devuelve «true» si el servidor está a la escucha de conexiones entrantes; en caso contrario, devuelve «false».
bool QBluetoothServer::listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0)
Comienza a escuchar las conexiones entrantes a address en port. address debe ser la dirección de un adaptador Bluetooth local y port debe ser mayor que cero y no estar ya ocupado por otro objeto de servidor Bluetooth. Se recomienda evitar especificar un número de puerto para que el sistema elija uno automáticamente.
Devuelve ` true ` si la operación se ha realizado correctamente y el servidor está a la escucha de conexiones entrantes; en caso contrario, devuelve ` false`.
Si el objeto servidor ya está a la escucha de conexiones entrantes, esta función siempre devuelve ` false`. Se debe llamar a ` close()` antes de llamar a esta función.
Véanse también isListening() y newConnection().
QBluetoothServiceInfo QBluetoothServer::listen(const QBluetoothUuid &uuid, const QString &serviceName = QString())
Función de conveniencia para registrar un servicio SPP en uuid y serviceName. Dado que esta función ya registra el servicio, el objeto QBluetoothServiceInfo que se devuelve ya no se puede modificar. Para apagar el servidor más adelante, es necesario llamar a QBluetoothServiceInfo::unregisterService() y close() en este objeto de servidor.
Devuelve una instancia registrada de ` QBluetoothServiceInfo ` si se realiza correctamente; de lo contrario, devuelve un ` QBluetoothServiceInfo` no válido. Esta función siempre asume que se debe utilizar el adaptador Bluetooth predeterminado.
Si el objeto servidor ya está a la escucha de conexiones entrantes, esta función devuelve un ` QBluetoothServiceInfo` no válido.
Para un servidor RFCOMM, esta función es equivalente al siguiente fragmento de código.
QBluetoothServiceInfo serviceInfo;
serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, serviceName);
QBluetoothServiceInfo::Sequence browseSequence;
browseSequence << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::PublicBrowseGroup));
serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
browseSequence);
QBluetoothServiceInfo::Sequence profileSequence;
QBluetoothServiceInfo::Sequence classId;
classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::SerialPort));
classId << QVariant::fromValue(quint16(0x100));
profileSequence.append(QVariant::fromValue(classId));
serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
profileSequence);
classId.clear();
//Android requires custom uuid to be set as service class
classId << QVariant::fromValue(uuid);
classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ServiceClassUuid::SerialPort));
serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
serviceInfo.setServiceUuid(uuid);
QBluetoothServiceInfo::Sequence protocolDescriptorList;
QBluetoothServiceInfo::Sequence protocol;
protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ProtocolUuid::L2cap));
if (d->serverType == QBluetoothServiceInfo::L2capProtocol)
protocol << QVariant::fromValue(serverPort());
protocolDescriptorList.append(QVariant::fromValue(protocol));
protocol.clear();
protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::ProtocolUuid::Rfcomm))
<< QVariant::fromValue(quint8(serverPort()));
protocolDescriptorList.append(QVariant::fromValue(protocol));
serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
protocolDescriptorList);
bool result = serviceInfo.registerService();Véase también isListening(), newConnection() y listen().
int QBluetoothServer::maxPendingConnections() const
Devuelve el número máximo de conexiones pendientes.
Véase también setMaxPendingConnections().
[signal] void QBluetoothServer::newConnection()
Esta señal se emite cuando hay una nueva conexión disponible.
La ranura conectada debe llamar a ` nextPendingConnection()` para obtener un objeto ` QBluetoothSocket ` con el que enviar y recibir datos a través de la conexión.
Véanse también nextPendingConnection() y hasPendingConnections().
QBluetoothSocket *QBluetoothServer::nextPendingConnection()
Devuelve un puntero al objeto ` QBluetoothSocket ` correspondiente a la siguiente conexión pendiente. Es responsabilidad del usuario que realiza la llamada eliminar dicho puntero.
QBluetooth::SecurityFlags QBluetoothServer::securityFlags() const
Devuelve los indicadores de seguridad de Bluetooth.
Véase también setSecurityFlags().
QBluetoothAddress QBluetoothServer::serverAddress() const
Devuelve la dirección del servidor.
quint16 QBluetoothServer::serverPort() const
Devuelve el número de puerto del servidor.
QBluetoothServiceInfo::Protocol QBluetoothServer::serverType() const
Devuelve el tipo del objeto ` QBluetoothServer`.
void QBluetoothServer::setMaxPendingConnections(int numConnections)
Establece el número máximo de conexiones pendientes en numConnections. Si el número de sockets pendientes supera este límite, se rechazarán los nuevos sockets.
Véase también maxPendingConnections().
void QBluetoothServer::setSecurityFlags(QBluetooth::SecurityFlags security)
Establece los indicadores de seguridad de Bluetooth en « security ». Esta función debe invocarse antes de llamar a ` listen()`. La conexión Bluetooth siempre estará cifrada cuando se utilicen dispositivos Bluetooth 2.1, ya que el cifrado es obligatorio.
En el backend BlueZ de Linux, los indicadores se asignan a los niveles de seguridad del núcleo:
- QBluetooth::Security::Authorization se asigna a «
BT_SECURITY_LOW»; - QBluetooth::Security::Encryption se asigna a
BT_SECURITY_MEDIUM; - QBluetooth::Security::Secure se asigna a
BT_SECURITY_HIGH; - QBluetooth::Security::Authentication no es utilizado por el núcleo y se ignora.
El valor por defecto es « QBluetooth::Security::Authorization ».
Android solo admite dos niveles de seguridad (seguro y no seguro). Si este indicador se establece en QBluetooth::Security::NoSecurity, el objeto servidor no empleará ninguna autenticación ni cifrado. Cualquier otra combinación de indicadores de seguridad activará una conexión Bluetooth segura.
En macOS y Windows, los indicadores de seguridad no son compatibles y se ignorarán.
Véase también ` securityFlags()`.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.