Home > other >  python socket in android fails to connect to python server run in virtualbox
python socket in android fails to connect to python server run in virtualbox

Time:11-13

I connected both my android phone and computer where a python server runs in a virtual box to the same Wifi. I can connect a client to a server in the same VirtualBox, but doesn't work from a phone. I have limited knowledge of networking. I suppose the IP address from server and client is the same and it should work. Could anyone give me some hints why it doesn't connect and maybe how to debug it please?

I type hostname -I in the terminal in my VirtualBox Ubuntu and get

10.0.2.15. 

I've added this in AndroidManifest.xml


 <uses-permission android:name="android.permission.INTERNET" /> 

python server code

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
port = 10050
socket_address = ('10.0.2.15',port)
server_socket.bind(socket_address)
server_socket.listen(5)
client_socket,addr = server_socket.accept()

android python client code (I use chaquo.python.android to run python script on android)

def connect():
    client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    host_ip = '10.0.2.15'
    port = 10050 
    client_socket.connect((host_ip,port))

the error on android

Process: com.example.simplecamera, PID: 17958
com.chaquo.python.PyException: TimeoutError: [Errno 110] Connection timed out

CodePudding user response:

If the code of python server is exact same as you are executing than the I would suggest you to change

client_socket,addr = server_socket.accept()

to

while True:
    client_socket,addr =server_socket.accept()
    print('[ ] connection from>>',addr)

The server will be needed to run continuously to connect and accept

so the program will look like

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
port = 10050
socket_address = ('10.0.2.15',port)
server_socket.bind(socket_address)
server_socket.listen(5)
while True:
    client_socket,addr =server_socket.accept()
    print('[ ] connection from>>',addr)
    #to close connection
    client_socket.close()
   

And have a look at https://github.com/dntfury/scaling-winner/blob/master/server_client_part_2/Server.py for exact similar server

  • Related