For bluetooth connection using PyBluez, socket connection is not getting accepted even after pairing
<p>I have a Raspberry pi model B booted with Rasbian OS and a bluetooth dongle plugged into it. I am able to discover my pi when searching from my PC and am able to pair using Blueman GUI. This is the python program I am using for the pairing process:</p>

<pre><code>from bluetooth import *

server_sock=BluetoothSocket(L2CAP)
server_sock.bind(("", 17))

with open(sys.path[0] + "/sdp_record.xml", "r") as fh:
        service_record = fh.read()
self.bus = dbus.SystemBus()
self.manager = dbus.Interface(self.bus.get_object("org.bluez", "/"),"org.bluez.Manager")
adapter_path = self.manager.DefaultAdapter()
self.service = dbus.Interface(self.bus.get_object("org.bluez",adapter_path),
                                                       "org.bluez.Service")
service_handle = service.AddRecord(service_record)
print "Service record added"
server_sock.listen(1)

print("Waiting for connection on L2CAP")

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

    while True:
        data = client_sock.recv(1024)
        if len(data) == 0:
                break
        print("received [%s]" % data)
except IOError:
    pass
except KeyboardInterrupt:
    print "Stopping..."
    stop_advertising(server_sock)
    sys.exit()  

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")
</code></pre>

<p>I already have a working SDP record, which is being read and it is added to the SDP server. 
At first when I posted this question I got this error:</p>

<pre><code>Traceback (most recent call last):
  File "pytest.py", line 4, in &lt;module&gt;
    server_sock.bind(("", 17))
  File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
    return self._sock.bind (addrport)
_bluetooth.error: (13, 'Permission denied')
</code></pre>

<p>This is because bluetooth needs root privileges. I ran the python code using <code>sudo python code.py</code> and this error was resolved. Thanks very much to guys who answered.</p>

<p>Now the problem I get is, the socket connection is not getting accepted even after pairing. For pairing, I run the code in one terminal and when it is <code>waiting for connection on L2CAP</code>, I open another console and pair the pi with my computer using the command <code>sudo bluez-simple-agent hci0 computers_macaddress</code>, it is getting paired after entering a pin in both the pi and computer. But after the pairing, the code is still waiting for connection:</p>

<pre><code>Service record added
Waiting for connection on L2CAP
</code></pre>

<p>It seems to be looping at that server_sock.accept() function. </p>

<p>Can anyone give a solution?</p>