HomePython Page 2 - Bluetooth Programming in Python: Network Programming using RFCOMM
Developing Applications for RFCOMM, Step by Step - Python
In the last article I discussed various Bluetooth profiles. If one wants to create a client-server based application using Bluetooth, then one should program for the RFCOMM profile. RFCOMM offers a socket-based client-server paradigm for providing services.
The steps necessary to develop RFCOMM-based applications can be divided into two main sets. They are creating the server and creating the client. Each of the steps can be again divided into sub-steps. Let us take each step one at a time.
Creating the Server
RFCOMM applications are essentially Bluetooth-based services. This has to be kept in mind when developing the server. The importance of this point will become clear in the steps regarding the client. Creating the server can be further divided into following steps:
Creating the Server Socket
Binding to a port
Listening for requests
Accepting the requests
Sending data
The steps are same as that for creating a TCP/IP-based server. However, the first and last step differs for RFCOMM. The details are as follows.
Creating the Server Socket
The first step is to create the socket that will listen for and accept incoming requests and create the connection. The sockets one would use when working with RFCOMM are Bluetooth sockets. To create a Bluetooth socket, BluetoothSocket needs to be called with the protocol to be used. In this case the protocol is RFCOMM. So, to create a socket named server_socket the statement will be:
This statement only creates a simple Bluetooth-based socket that uses RFCOMM for communication. The next three steps make it a server socket.
Binding to a Port
This is the second step to making a simple socket work as a server socket. The socket object needs to be bound to an address and a port so that it can start listening for requests. However, since the socket will be communicating over Bluetooth, an IP address is not required. PyBluez will use the address of the device on which it is running. If the device is a desktop PC, then the address will correspond to the address provided by the Bluetooth adapter or dongle.
To bind a socket object to a port, the bind() method needs to be called on the socket object. The argument passed is a tuple containing the address and the port number with which the socket has to be bound. For example, to bind a socket to a port, say 11, the statement will be
server_socket.bind(("",11))
One point to keep in mind while working with RFCOMM is that RFCOMM uses ports between 1-30 only.