I am a beginner in socket programming. I wrote a Python code that creates a socket listening on port 12345 :
port=12343
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
IP = '0.0.0.0'
s.bind((IP,port))
s.listen(nb_max_connex)
print(f"Le serveur est lancé sur {IP} sur le port {port}.")
connexion,addresse=s.accept() #accepter la connexion
print("Connecté à ",addresse)
Here is my java code :
Socket soc=new Socket("10.0.2.2",12343);
if(soc.isConnected()){
CharSequence text = "La connexion avec le système a été réalisée";
Context context = GlobalApplication.getAppContext();
Log.d("CONNECT","connecté au socket");
//Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
}
10.0.2.2 works well with android emulator, the connection is successful. However when I install my app on my phone, I can't determine how the connection can be made, I have tried using Socket soc=new Socket("127.0.0.1",12343) but there is no connection...
Could someone help me out ?
CodePudding user response:
For this, to work, you need your laptop and mobile to connect to the same network. Then get your laptop's local IP address like below.
How to get your IP address:
On windows Open command prompt-> type ipconfig --> copy you device IP read this for more https://support.microsoft.com/en-au/windows/find-your-ip-address-in-windows-f21a9bbc-c582-55cd-35e0-73431160a1b9
On Linux and Mac open terminal -> type ifconfig --> copy you device ip read this for more https://www.macworld.co.uk/how-to/ip-address-3676112/#:~:text=the search bar.-,How to find your local internal (private/local) IP address,-The IP address
Socket soc=new Socket("laptop-ip-address",12343);
if(soc.isConnected()){
CharSequence text = "La connexion avec le système a été réalisée";
Context context = GlobalApplication.getAppContext();
Log.d("CONNECT","connecté au socket");
//Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
}