QBluetoothServer Class
La clase QBluetoothServer utiliza el protocolo RFCOMM o L2cap para comunicarse con un dispositivo Bluetooth. Más...
| Cabecera: | #include <QBluetoothServer> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Bluetooth)target_link_libraries(mytarget PRIVATE Qt6::Bluetooth) |
| qmake: | QT += bluetooth |
| Hereda: | 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 sobre RFCOMM o L2cap.
Empieza a escuchar conexiones entrantes con listen(). Espera a que se emita la señal newConnection() cuando se establece 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 aplicables a tu servicio y regístralo mediante QBluetoothServiceInfo::registerService(). Llama a serverPort() para obtener el número de canal que se está utilizando.
Si QBluetoothServiceInfo::Protocol no está soportado por una plataforma, listen() devolverá false. Android y WinRT sólo soportan RFCOMM, por ejemplo.
En iOS, esta clase no se puede utilizar porque la plataforma no expone una API que pueda permitir el acceso a las funciones relacionadas con QBluetoothServer.
Véase también QBluetoothServiceInfo y QBluetoothSocket.
Documentación de tipos de miembros
enum QBluetoothServer::Error
Este enum 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 puerto ya estaba registrado. |
QBluetoothServer::UnsupportedProtocolError | 5 | Protocol no es compatible con esta plataforma. |
QBluetoothServer::MissingPermissionsError (since Qt 6.4) | 6 | El sistema operativo solicita permisos que no fueron concedidos por el usuario. |
Documentación de las funciones miembro
[explicit] QBluetoothServer::QBluetoothServer(QBluetoothServiceInfo::Protocol serverType, QObject *parent = nullptr)
Construye un servidor bluetooth con parent y serverType.
[virtual noexcept] QBluetoothServer::~QBluetoothServer()
Destruye el servidor bluetooth.
void QBluetoothServer::close()
Cierra y reinicia el socket de escucha. Cualquier QBluetoothSocket ya establecido continúa funcionando y debe ser closed por separado.
QBluetoothServer::Error QBluetoothServer::error() const
Devuelve el último error de la 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 false.
bool QBluetoothServer::isListening() const
Devuelve true si el servidor está a la escucha de conexiones entrantes, en caso contrario false.
bool QBluetoothServer::listen(const QBluetoothAddress &address = QBluetoothAddress(), quint16 port = 0)
Empieza a escuchar conexiones entrantes a address en port. address debe ser una dirección de adaptador Bluetooth local y port debe ser mayor que cero y no estar tomada ya por otro objeto servidor Bluetooth. Se recomienda evitar establecer un número de puerto para permitir que el sistema elija un puerto automáticamente.
Devuelve true si la operación ha tenido éxito 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. Antes de llamar a esta función, debe invocarse a close().
Véase también isListening() y newConnection().
QBluetoothServiceInfo QBluetoothServer::listen(const QBluetoothUuid &uuid, const QString &serviceName = QString())
Función de conveniencia para registrar un servicio SPP con 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 tarde es necesario llamar a QBluetoothServiceInfo::unregisterService() y close() en este objeto servidor.
Devuelve una instancia registrada de QBluetoothServiceInfo si tiene éxito, en caso contrario, un QBluetoothServiceInfo inválido. Esta función siempre asume que se debe utilizar el adaptador Bluetooth por defecto.
Si el objeto servidor ya está escuchando 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 para enviar y recibir datos a través de la conexión.
Véase también nextPendingConnection() y hasPendingConnections().
QBluetoothSocket *QBluetoothServer::nextPendingConnection()
Devuelve un puntero a QBluetoothSocket para la siguiente conexión pendiente. Es responsabilidad de quien llama eliminar el 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 de QBluetoothServer.
void QBluetoothServer::setMaxPendingConnections(int numConnections)
Establece el número máximo de conexiones pendientes en numConnections. Si el número de conexiones pendientes supera este límite, se rechazarán nuevas conexiones.
Véase también maxPendingConnections().
void QBluetoothServer::setSecurityFlags(QBluetooth::SecurityFlags security)
Establece los indicadores de seguridad Bluetooth en security. Esta función debe llamarse antes de llamar a listen(). El enlace Bluetooth siempre estará cifrado cuando se utilicen dispositivos Bluetooth 2.1, ya que el cifrado es obligatorio.
Android sólo soporta dos niveles de seguridad (seguro y no seguro). Si esta bandera se establece en QBluetooth::Security::NoSecurity el objeto servidor no empleará ningún tipo de autenticación o encriptación. Cualquier otra combinación de indicadores de seguridad activará una conexión Bluetooth segura.
En macOS, los indicadores de seguridad no están soportados y serán ignorados.
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.