BluetoothError: (111, 'Connection refused')

I'm trying to connect raspberry pi 4 to my ubuntu laptop. I setup a rfcomm server on my laptop, the code is given below:

import bluetooth

server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE],
# protocols=[bluetooth.OBEX_UUID]
)

print("Waiting for connection on RFCOMM channel", port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)

try:
while True:
data = client_sock.recv(1024)
if not data:
break
except OSError:
pass

print("Disconnected.")

client_sock.close()
server_sock.close()
print("All done.")


And I setup a rfcomm client on the pi:

import sys
import bluetooth

uuid = ""
service_name='SampleServer'
service_matches = bluetooth.find_service(name=service_name)

if len(service_matches) == 0:
print("couldn't find the FooBar service")
sys.exit(0)

first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

print("connecting to {} on {}".format(name, host))

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((host, port))
sock.send(b"hello!!")
sock.close()


I started the server first, however, when I ran the client, I found that the pi connected to my laptop for only a short time, and then the connection broke, and got the error: bluetooth.btcommon.BluetoothError: (111, 'Connection refused').

I've read some similar questions here, but they all seem to have set the mac address for server mistakenly, which is not what I did. So what's my problem here?

• "Connection refused" has three possible reasons. 1. Wrong address, 2 Right address, wrong port. 3. Right address, right port listener not listening, – Dougie May 28 '20 at 9:21
• Do you ask how to setup a rfcomm server on your laptop? – Ingo May 28 '20 at 17:11
• @Ingo not yet... Do you mean I may get a hint from that? – null May 29 '20 at 2:31
• I'm asking because I can't see a problem on the RasPi from your description. Configuring a rfcomm server is out of scope on Raspberry Pi. Can you please elaborate where the problem could be on the RasPi? – Ingo May 29 '20 at 18:08