Running Python socket script through ADB - android

I have a somewhat unusual problem. I want to run some code on my android smartphone via the ADB (which along with SL4A is already set up) and then I want it to act as a server and respond with the program's results while my host machine acts as a client and receives this data. However, I am not an expert in socket operations and I'm getting results I don't understand. My code is as follows:
from device import android
import socket
droid = android.Android()
# Open socket
s = socket.socket()
HOST = socket.gethostname()
PORT = 8000
s.bind((HOST, PORT))
s.listen(5)
print "HOST = ", HOST, ", PORT = ", PORT
# Accept instructions
c, addr = s.accept()
print "Got connection from", addr
data = ""
while True:
chunk = c.recv(1024)
if (not chunk):
break
else:
data.extend(chunk)
s.close()
# DO STUFF WITH RECEIVED INPUT
# Send result
c, addr = s.accept()
print "Got connection from", addr
while True:
if (c.send(str(result)):
break
s.close()
The code I'm running on the client, my host machine, is as follows:
s = socket.socket()
HOST = "localhost"
PORT = 8000
s.connect((HOST, PORT))
s.send(data)
s.close()
# IN A DIFFERENT FUNCTION
s = socket.socket()
HOST = "localhost"
PORT = 8000
try:
s.connect((HOST, PORT))
results = s.recv(1024)
s.close()
return results
except Exception:
return False
The environment has been set up this way:
set AP_PORT=54023
adb forward tcp:%AP_PORT% tcp:%AP_PORT%
So, how this is supposed to work is this: the server is set up to run on my Android smartphone and accept input to run the program on my Android smartphone from another program running on my PC. After the Android program has finished running, it should send the result back to my PC.
However, I'm having several problems. I can't seem to get the first connection open. I either get 10061's or 10049's and I'm not sure why that is. I've looked at the existing documentation available and I'm still not getting results. I'm also not sure if this code is actually running on the Android device and this is very important to my application so I really need some sort of confirmation on this.
Any enlightenment would be greatly appreciated.

The server program never ends until it reaches an exception, because you set up an inf loop: while True.
c.close() close the current connection, then the loop starts again and the program waits for another connection to accept.
The host program instead should end after the message is sent or when it reaches an exception.
What do you mean with: " I'm getting results I don't understand... This code runs without error... The problem I'm having is that I'm not getting any results back"?
What results do you get? Have you checked the data var?

Related

Unable to connect to socket over wifi connection

I am not able to connect to socket on Raspberry Pi 3 B+. This is what I did
Installed dnsmasq and hostapd and configured
created an access point and assigned static ip to wlano as 192.168.4.1 without bridging to lan
started a python script to listen on port 8888 (is successfully waiting for connections)
created an Android app to connect to the access point and send message over socket to 192.168.4.1 on port 8888
When I tried to connect to the socket using the wlan0 static ip,192.168.4.1 I am getting unknown host exception. and the python script prints the socket ip as 127.0.1.1 how can I run the Python script to listen on wlan0 IP instead of 127.0.1.1 this is my Python script which I got from internet
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
I haven't done any Python programming earlier. So I have to rely on the script and it is working fine.
Set
HOST = "192.168.4.1"
In the code and it should work.

Receiving messages over bluetooth to raspberrypi

I would like to receive the messages from my phone to raspberry over bluetooth
I have written the following code ,
import bluetooth
hostMACAddress = '18:9E:FC:A1:81:93' # The MAC address of my iphone
port = 3
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
client.send(data) # Echo back to client
except:
print("Closing socket")
client.close()
s.close()
How can i receive the messages to my Raspberry when i run this code, i see no messages being received, my raspberry detects the MAC address of my iPhone but i would like to send some message and see if the bluetooth of raspberry can receive it
Kindly let me know what modifications i have to do in this code in order to achieve bluetooth connection
I haven't completed building an app using Flutter but I have the server/client code ready using python.
Server.py
import socket
import os
import multiprocessing
from multiprocessing import pool
os.system('sudo python3 relay.py C') #runs relay program and setups up GPIO pins
hostMACAddress = 'B8:27:EB:A3:B6:EB' # The MAC address of a Bluetooth adapter on the server.
backlog = 4
port=3
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((hostMACAddress,port))
s.listen(backlog)
def new_client(client):
while 1:
data = client.recv(size)
if data:
n=data.decode("utf-8")
if n == 'ON':
os.system('sudo python3 relay.py ON')
if n == 'OFF':
os.system('sudo python3 relay.py OFF')
if n == 'CLOSE':
break
client.send(data)
if __name__ == '__main__':
client, address = s.accept()
pool = multiprocessing.Pool(4)
pool.map(new_client, (client, ))
pool.close()
pool.join
print("Closing socket")
client.close()
s.close()
This is my server program running on raspberry pi.
I implemented multithreading to allow 4 active connections(sockets) at all time, since bluetooth is a little different than web socket programming I had to get creative to keep the application running after any client closes connection.
Basically if I get the message ON/OFF, it in turn runs another python program that turn the relay on or off, if I get CLOSE message, I terminate the thread.
Client.py
import bluetooth
bd_addr = 'B8:27:EB:A3:B6:EB'
port = 3
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
print("Connected")
while True:
try:
data = input()
sock.send(data.encode())
if data == 'CLOSE':
break
except KeyboardInterrupt:
sock.close()
This is my client program running on my computer.
Notice the address in both codes in the same(MAC Address of my raspberry pi), because raspberry pi need the address of the bluetooth adapter to use(in case some machines have multiple interfaces) and client needs server bluetooth MAC Address in order to initiate socket connection. You also need to port that you configured in raspbery pi to receive connection in my case 3.
Let me know if you need any additional information.
Have fun making an app that implements socket programming!

TCP/IP on an Android Device using Python Socket

I have a Python script that is running on Android-SL4A that returns the values from the orientation sensor. I would like to transfer those values as text to a raspberry pi 2B+. While I have some Python skills I am unfamiliar with TCP/IP but I found this code below, and similar code to run on the receiving device. While testing the code below, the listening code on a Windows PC appears to be listening just fine but when I execute the sending code (posted below) on the Android device it gives a error at
s.connect((TCP_IP, TCP_PORT))
I receive an error(Errno 111) that the connection was refused.
Any help debugging would be great.
import time, math, sys, traceback
import socket
print "imports done"
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
print "settings defined"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "socket created"
s.connect((TCP_IP, TCP_PORT))
print "connection made"
print "message sent"
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
print "All Done"
If you don't want to learn how low-level sockets work, you can always use someone else's library.
The popular ones with TCP support are Tornado and Twisted, but I suggest you use simpleTCP, as it doesn't require you learn an entire framework to simply send information over TCP. The project website has the 5-line program for an echo server and an even smaller example of client sockets on its front page.

Suddenly unable to create socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
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.
print "entered loop"
c, addr = s.accept() # Establish connection with client.
I was using this piece of code to simply create a socket and accept a connection on it from an Android. Simple enough.
But since the past few hours (with no changes to the code), python is for some reason unable to create the socket. I don't get any errors, but it's forever stuck at the s.accept() line.
I tried using Fing, a network diagnostics app on my Android to see the open ports, and indeed, Python is unable to create/open the socket. Earlier, as soon as I ran the code and rescanned on Fing, I was able to see the port open and test a TCP connection on it.
Sometimes, randomly in between, it works for one or two attempts.
What could be going wrong? I've tried to change port. I don't know what to debug since there isn't any error!
Same Error occur to me . it was due to not closing the Socket . Try Closing the Sockets.
Else it will work for once when ever you will run and then after that it will start causing problems.

Python Socket transfer speed too low

I'm running Python on my Android 2.3 powered HTC phone using SL4A ... so I wrote a code to retrieve accelerometer values and send them to my pc via Sockets ! The problem is that on phone the code gets values each 100ms and I'm using a while loop to keep sending them to PC. But the pc doesn't get the values at the same speed, I mean it's slower, and just to keep in mind that I modified the values to be like so :
> [0.0,1.0,-5.0]
> [0.0,2.0,-2.0] a list of Rounded floats
> ...
and here is my server code (running on pc):
import socket
HOST = ""
PORT = 55600
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
print data
if not data: break
conn.close()
Any help to make it faster ?
The first thing I would change is getting rid of the print statement in your loop. IO is very slow. This is, of course, assuming you're planning on doing something with these values besides display them to the screen ;)

Categories

Resources