I would like to make a bluetooth communication between a laptop with a bluetooth dongle and windows 7, and my raspberry pi 3.
I found on internet some tutorials which use the Pybluez librairy but this doesn't work for me.
Find below the code for the server part :
import bluetooth
Host = ""
port = 12
HostAddr = (Host, port)
def setupServer():
server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
print("Socket Created.")
server_socket.bind(HostAddr)
server_socket.listen(1)
print("Socket bind complete")
client_sock, client_info = server_socket.accept()
print("Accepted connection from " , client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" %data)
except IOError:
pass
print("Disconnected")
client_sock.close()
server_socket.close()
print("all done")
setupServer()
This is the output :
Socket Created.
Traceback (most recent call last):
File "path_to_file\Server.py", line 33, in <module>
setupServer()
File "path_to_file\Server.py", line 12, in setupServer
server_socket.bind(HostAddr)
File "C:\Python34\lib\site-packages\bluetooth\msbt.py", line 60, in bind
bt.bind (self._sockfd, addr, port)
OSError
Do you have an idea why i had this error ?
Related
Currently I'm working on a live chat program. I've followed a tutorial online, and the outcome was a working live chat.
It consists of a server file and a client file.
The error happens when i close the client file and join the same server instance.
From the client side i can't send a message. In the server commandprompt it gives this error:
Waiting for connection...
192.168.0.81:61453 connected to server.
192.168.0.81:61456 connected to server.
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Rasmus\Desktop\Programmering\troubleshoot\server.py", line 19, in handle_client
broadcast(bytes(msg, "utf8"))
File "C:\Users\Rasmus\Desktop\Programmering\troubleshoot\server.py", line 36, in broadcast
sock.send(bytes(prefix, "utf8")+msg)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
As far as I can read on the internet, it is because there is an active connection from the same adress. Does this mean the program doesn't close the client properly?
This problem also occurs, when other clients from other networks connect.
I'm not quite a newbie but neither an expert at Python, so in dept explanation is much appreciated.
Server.py:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print("%s:%s connected to server." % client_address)
client.send(bytes("Type your name and press enter.", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client):
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! Type {stop} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s connected to the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{stop}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{stop}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s leaved the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
clients = {}
addresses = {}
HOST = '192.168.0.81'
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
Client.py:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
def receive():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
msg_list.insert(tkinter.END, msg)
except OSError:
break
def send(event=None):
msg = my_msg.get()
my_msg.set("")
client_socket.send(bytes(msg, "utf8"))
if msg == "{stop}":
client_socket.close()
top.quit()
def on_closing(event=None):
my_msg.set("{stop}")
send()
top = tkinter.Tk()
top.title("Corona chat")
messages_frame = tkinter.Frame(top)
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()
my_msg = tkinter.StringVar()
my_msg.set("")
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()
I have 3 devices -> 2*PC and 1 Raspberry Pi. 2 PCs are only for the sake of testing. 2PC = 2 Laptops with Windows 10.
On raspberry pi I have Bluetooth service(Py 2.7 but 3.5 should also work if print()):
import bluetooth
try:
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
server_sock.bind(("",0))
server_sock.listen(100)
bluetooth.advertise_service( server_sock, "MyService",
service_classes = [ bluetooth.SERIAL_PORT_CLASS ],
profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
client_sock.send('Hello')
data = client_sock.recv(1024)
print("received [%s]" % data)
client_sock.close()
server_sock.close()
except:
client_sock.close()
server_sock.close()
On Laptops I have client
import sys
from bluetooth import *
try:
service_matches = find_service(name="MyService",
uuid = SERIAL_PORT_CLASS )
print(service_matches)
if len(service_matches) == 0:
print('Found nothing')
sys.exit(0)
for i in service_matches:
print(i)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print "connecting to ", host
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
data = sock.recv(1024)
sock.send("hello!!")
print(data)
sock.close()
except Exception as e:
print(e)
sock.close()
Everything works just fine, however, with one laptop I can repeat the proces between listening and connecting forever. With other Laptot I am able to connect 2-3 times and then I am receiving this error:
in <module>
uuid = SERIAL_PORT_CLASS )
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 204, in find_service
addresses = discover_devices (lookup_names = False)
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 15, in discover_devices
devices = bt.discover_devices(duration=duration, flush_cache=flush_cache)
IOError: No more data is available.
That means the error happened inside the pybluez function find_service. Interesting is that this happens when it cannot find a device. On the other laptop where this error is never triggered(always connects) but there are no devices ends up always with:
print('Found nothing')
When the error starts to happen after 2-3 succesful connections, I need to restart Raspberry pi to be able to connect again.
Thanks for any help
I have tried to create a simple socket program where I can enable back and forth communication between two server sockets. The first iteration runs successfully and then there is one set of message passing that is possible. When it comes to second round of message passing I get the error.
I feel there is some mistake in the IP Address but I could not resolve it.
I have looked here but could not find a solution
OSError: [Errno 99] Cannot assign requested address - py
Python - socket.error: Cannot assign requested address
Any help is deeply appreciated
This is Server 1:
import socket
import requests
host = "127.0.0.1"
#ip address
port_other_send = 5007
#Other's port while sending
port_own_send = 5006
#Our port for sending
port_other_recieve = 5009
#other port for recieving
port_own_recieve = 5008
#our port for recieving
#s = socket.socket()
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#s.bind(("", port_own))
#binds the socket element to the IP address and the Port
def main():
send()
def send():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port_own_send))
s.connect((host,port_other_recieve))
message = input("Type message to be sent ")
while message != "q":
s.send(message.encode('utf-8'))
break
receive()
def receive():
print("This works yo")
socketva = socket.socket()
socketva.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketva.bind((host, port_own_recieve))
socketva.listen()
c,addr=socketva.accept()
x = True
while x ==True:
print("Connection from",(addr))
data = c.recv(1024)
print ("Data recieved ", str(data))
response= ("Data recieved")
c.send(data)
x = False
c.close
send()
if __name__ == "__main__":
main()
This is server 2:
import socket
import flask
host = "127.0.0.1"
#ip address
port_other_send= 5006
#Other's port while sending
port_own_send= 5007
#Our port for sending
port_other_recieve = 5008
#other port for recieving
port_own_recieve=5009
#our port for recieving
#binds the socket element to the IP address and the Port
def main():
receive()
def receive():
socketva = socket.socket()
socketva.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketva.bind((host, port_own_recieve))
socketva.listen()
c,addr=socketva.accept()
x = True
while x== True:
print("Connection from",(addr))
data = c.recv(1024)
print ("Data recieved: ",data)
response= ("Data recieved")
c.send(data)
x= False
c.close
send()
def send():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port_own_send))
s.connect(("",port_other_recieve))
message = input("Enter reply message ")
while message != "q":
s.send(message.encode('utf-8'))
receive()
if __name__ == "__main__":
main()
Server 1 Output:
Type message to be sent hi
This works yo
Connection from ('127.0.0.1', 5007)
Data recieved b'hihihihihihihihihihihihihihihihihi'
Traceback (most recent call last):
File "Server_socket.py", line 100, in <module>
main()
File "Server_socket.py", line 57, in main
send()
File "Server_socket.py", line 68, in send
receive()
File "Server_socket.py", line 87, in receive
send()
File "Server_socket.py", line 63, in send
s.connect((host,port_other_recieve))
OSError: [Errno 99] Cannot assign requested address
Server 2 Output:
Connection from ('127.0.0.1', 5006)
Data recieved: b'hi'
Enter reply message hi
Traceback (most recent call last):
File "Server_socket2.py", line 54, in <module>
main()
File "Server_socket2.py", line 23, in main
receive()
File "Server_socket2.py", line 41, in receive
send()
File "Server_socket2.py", line 50, in send
s.send(message.encode('utf-8'))
ConnectionResetError: [Errno 104] Connection reset by peer
So, im trying to make a little program which shows message boxes with messages i send it. and it works, but when i clientside close the connection the server script exits and i get this message:
Traceback (most recent call last): File "server.py", line 9, in <module>
conn, addr = s.accept() File "C:\Python27\lib\socket.py", line 206, in accept
sock, addr = self._sock.accept() KeyboardInterrupt
this is my python code:
import socket
from appJar import gui
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1337 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
data = conn.recv(1024)
if not data: break
app=gui("Besked fra Romeo")
app.addLabel("idk",data)
app.go()
how do i stop the server script from closing when i close my clientside script?
KeyboardInterrupt is just an exception. You should be able to catch it:
try:
# Your loop
except KeyboardInterrupt:
# Code that gets executed when ctrl-c is pressed
There is an error in my client side code. The error is,"The operation was attempted on something that is not a socket." how do I go about fixing this error. I also know that my input is not sent to the server yet, If you guys have any tips on how I accomplish that I would also love them. Thanks! The code showed below:
import socket, select, string, sys
def prompt() :
sys.stdout.write('<You> ')
sys.stdout.flush()
#main function
if __name__ == "__main__":
host = "localhost"
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print('Unable to connect')
sys.exit()
print('Connected to remote host. Start sending messages')
prompt()
input = input()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print('\nDisconnected from chat server')
sys.exit()
else :
#print data
sys.stdout.write(data)
prompt()
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)
prompt()
Server Code:
import socket, select
#Function to broadcast chat messages to all connected clients
def broadcast_data (sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ == "__main__":
# List to keep track of socket descriptors
CONNECTION_LIST = []
RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", PORT))
server_socket.listen(10)
# Add server socket to the list of readable connections
CONNECTION_LIST.append(server_socket)
print("Chat server started on port " + str(PORT))
while 1:
# Get the list sockets which are ready to be read through select
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
#New connection
if sock == server_socket:
# Handle the case in which there is a new connection recieved through server_socket
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print("Client (%s, %s) connected" % addr)
broadcast_data(sockfd, "[%s:%s] entered room\n" % addr)
#Some incoming message from a client
else:
# Data recieved from client, process it
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
if data:
broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print("Client (%s, %s) is offline" % addr)
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
On Microsoft Windows, python's socket library is implemented using Winsock. Winsock isn't integrated into the operating system like the sockets library on unixy systems. It has its own idea of what a socket is, and does not recognize system pipes or consoles.
On Windows you get the error you see
>>> import platform
>>> print platform.system()
Windows
>>> import socket
>>> import select
>>> import sys
>>> select.select([sys.stdin],[],[])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
select.error: (10038, 'An operation was attempted on something that is not a socket')
>>> select.select([sys.stdin.fileno()],[],[])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
select.error: (10038, 'An operation was attempted on something that is not a socket')
>>>
On linux it works
>>> import platform
>>> print platform.system()
Linux
>>> import socket
>>> import select
>>> import sys
>>> select.select([sys.stdin],[],[],0)
([], [], [])
>>>
I couldn't see anything wrong so I ran your code on my linux box with python3.4 and got no errors from either server or the client and they connected without issue. The only thing I can think of is with your version of python or OS like tdelaney suggested. I don't have a windows box to test with so I can't confirm if it's OS specific.
Use input = [s] #instead of socket_list = [sys.stdin, s]