I am attempting to make a simple bluetooth program in python using pybluez. For the server script I have this code:
import bluetooth as bt
HOST = ""
PORT = 8888
s = bt.BluetoothSocket(bt.RFCOMM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
print("Connected by", addr)
while True:
data = conn.recv(1024)
print(data)
When I attempt to run it I get the Error:
OSError: The requested address is not valid in its context.
I have done extensive research and am unable to find any real cause; it seems to be that pybluez doesn't like to be bound to the address "", but every example I found online said to do that.
I figured out my problem. For RFCOMM connections, the port needs to be even and between 1 and 30. Sorry for any inconvenience.
Related
I m trying to read data from a GPS device "Telonika FMB204" using a python socket and TCP/IP
all you have to do as setup is to specify the server IP and the port the start my python I found Telonika forum showing data received successfully, I try to test it using my dynamic IP address but I the script shows no data my question is there any way to host the script somewhere ?
link :https://community.teltonika-gps.com/4965/how-to-read-data-from-teltonika-fmb001-with-a-python-script
import socket
port = 3000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
print('Connected by ', addr)
imei = conn.recv(1024)
conn.send('\x01')
while True:
try:
data = conn.recv(1024)
if not data:
break
f = open("demofile2.txt", "a")
f.write(data)
f.close()
print(data)
except socket.error:
print("Error Occured.")
break
Receiving data from GPS Device will work only on computer with a fixed IP address (you can use no-ip service and open port on your router in my case the port 3000 ) or you can buy a VPS server open the port and you are ready to go
hope those informations will help ;)
I am trying to build a connection between a server and one or more clients in Python using sockets. My code works just fine when I connect with a client in the same network, but my goal is to build a program which me and my friend can use, so I want to figure out a way to connect to my server from an external network via the internet.
My server-side code looks like this:
import socket
server = "internal_ip"
port = 5006
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serv.bind((server, port))
print(server)
except socket.error as e:
print(e)
serv.listen(2)
while True:
conn, addr = serv.accept()
from_client = ""
while True:
data = conn.recv(4096)
if not data:
break
from_client += str(data)
print(from_client)
conn.send(str.encode("I am SERVER"))
conn.close()
print("Client disconnected")
And this is my client:
import socket
server = "internal_ip"
port = 5006
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((server, port))
except socket.error as e:
print(e)
while True:
try:
client.send(str.encode("I am CLIENT"))
from_server = client.recv(4096)
#client.close()
print(from_server)
except:
break
client.close()
This works just fine within a network. Then I started testing the code from an external client. I changed the ip to my external ip address which I have found using whatismyipaddress.com, and port number to a different one than I use on the server side.
server = "external_ip"
port = 5007
Then I enabled port forwarding using cmd:
netsh interface portproxy add v4tov4 listenport=5007 listenaddress=external_ip connectport=5006 connectaddress=internal_ip
I get WinError 10060. Tried switching firewall on and off, and allowing these specific ports, but I can't make it work.
Can you help me with my problem please?
I'm reading about socket module in a web learning site about python, they gave us a simple steps to use socket module like follows:
import socket
with socket.socket() as client_socket:
hostname = '127.0.0.1'
port = 9090
address = (hostname, port)
client_socket.connect(address)
data = 'Wake up, Neo'
data = data.encode()
client_socket.send(data)
response = client_socket.recv(1024)
response = response.decode()
print(response)
when executing I got the error message:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it.
when I searched about this some sites was talking about server listening and I see in most of tutorials about server socket and they use it along with client one.
so Is the error message related to the fact that I'm not using a server socket and is it a must to use them both
Update:
after reading the answers I got, I went to the test.py file that the course instructors use to evaluate our codes and I see that they make the server socket in it , so the server is already made by them. that take me back to the Error I got why does it happen then.
def server(self):
'''function - creating a server and answering clients'''
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('localhost', 9090))
self.ready = True
try:
self.sock.listen(1)
conn, addr = self.sock.accept()
self.connected = True
conn.settimeout(15)
while True:
data = conn.recv(1024)
self.message.append(data.decode('utf8'))
if len(self.message) > 1_000_000:
conn.send(
json.dumps({
'result': 'Too many attempts to connect!'
}).encode('utf8'))
break
if not data:
break
Each connection requires a client, which initiates the connection, and a server, which listens for the incoming connection from the client. The code you have shown is for the client end of the connection. In order for this to run successfully you will need a server listening for the connection you are trying to create.
In the code you showed us you have the lines
hostname = '127.0.0.1'
port = 9090
address = (hostname, port)
client_socket.connect(address)
These are the lines that define what server you are connecting to. In this case it is a server at 127.0.0.1 (which is localhost, the same machine you are running the code on) listening on port 9090.
If you want to make your own server then you can look at the documentation for Python sockets and the particular functions you want to know about are bind, listen, and accept. You can find examples at the bottom of that same page.
Given that you appear to have found this code as part of a course, I suspect they may provide you with matching server code at some point in order to be able to use this example.
I am new to python coding and tried to create a simple python socket server.
I coded a client.py and a server.py on my laptop and it seems to work (It does what it is supposed to do....), but if i try to run the server on my laptop and the client on my other computer, it sometimes times out.
client.py
import socket
s = socket.socket()
host = '192.168.178.87'
port = 12345
s.connect((host, port))
print s.recv(1024)
s.sendall("greetings")
server.py
import socket
s = socket.socket()
host = ''
port = 12345
s.bind((host, port))
s.listen(5)
i = 0
while i < 5:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
data = c.recv(1024)
print data
c.close()
i += 1
print i
s.close()
I am using a FritzBox 7390, Both computers are in the same local network, both firewalls are turned off and no antivirus is installed.
I am using windows 7 and python 2.7 on both computers.
My problem summed up:
If I run the server on my laptop(192.168.178.87) and open the client.py via cmd on the same computer , it works (I tried to use 127.0.0.1, 192.168.178.87 and my official ipv4 address(portforwarding in the router)) and everything works.
But if I try to use the client.py on my other computer (192.168.178.131) it only works if I am the fifth to try to connect and I have no idea why.
I can connect to the server via browser, and it sometimes works, but mostly there is an timeout error (Errno 10060).
What is the problem with my code?
I am new to opening a port and server side programming. And I am trying to open a port on my server in python and then form an iOS app get some data from that port. I have done some research and know I can open a port like this
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
But my question is lets say I just wanted to retrieve a simple string from this port how do I add that string to this open port, I have found some ways to get data from the port in iOS like this library https://github.com/armadsen/ORSSerialPort but how do I put the data like a string on the open port?
Thanks for the help in advance.
When you call the method s.accept() it will return the socket object as the first return. You can call socket.rescv method to read data -
data = c.recv(1024)
But do remember this is a blocking call. For more information, you can read this post.