3

I created simple bluetooth RFCOMM server on Python 3

Here is my code:

import bluetooth

class Bluetooth:
    def __init__(self, port, backlog, size):
        #backlog =  number of users who can connect to socket at the same time
        #size = message size
        s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        s.bind(("", port))  #(mac addres, port)
        s.listen(backlog)
        print("Server is active, waiting for connection!")

        while True:
            client, clientInfo = s.accept()
            print("Connected with :", clientInfo)
            try:
                while True:
                    data = client.recv(size)
                    if data:
                        print(data)
            except:
                print("Closing socket")
                client.close()
            print("Waiting for connection!")

        s.close()
        print("Server closed!")

When I send data from android device app like BlueTerm, BlueTerm2, Bluetooth Terminal (...) I get b'my string' Screenshot from PyCharm

Screenshot from PyCharm

What does the b sign preceding my text data mean? How I can print only my string?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Does this answer your question? [How to convert 'binary string' to normal string in Python3?](https://stackoverflow.com/questions/17615414/how-to-convert-binary-string-to-normal-string-in-python3) – f9c69e9781fa194211448473495534 Sep 24 '20 at 22:14

1 Answers1

0

Basically client.recv(N) waits for N bytes of data to be sent. So, in the end what you get is byte string (and not string in utf-8 or ascii etc.).

Answering to the question b preceding the data is specifying that it's of byte string type.

In-order to convert byte string to string you can use

byte_data = client.recv(size)
data = byte_data.encode('utf-8') # to encode data in utf-8 format