简体   繁体   中英

Socket writing java (android) to python

I want to create a super basic Android App that connects to a python server running on my PC but the python server never gets the connection

my java code:

public class WriteToSocket {
Socket sock;

public void Test() {
    try {
        this.sock = new Socket("PCName", 9871);

    } catch (UnknownHostException e) {
        System.out.println("Unknown host: PCName");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
    }
}

public void Test1(){
    try {
        this.sock.close();
    } catch (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
    }
}

and

public void onClick(View v) {
    WriteToSocket a = new WriteToSocket();
    a.Test();

}

and my python server is

import socket

sock = socket.socket()
name = "PCName"
port = 9871

sock.bind((name,port))
sock.listen(1)
s,a = sock.accept()

I expected after the button click for the python server to accept the connection (I also tried changing "PCName" to "127.0.0.1")

I've looked around but nothing helped me so far :S

Bind your server socket to one of the IP addresses of your PC which is accessible from your android, and not to 127.0.0.1. Or alternatively bind it to all available interfaces (0.0.0.0).

Then connect from your android to that IP.

Eg if your PC has IP address 1.2.3.4 then use this IP in both applications.

Use netstat to see if the port is really open on your PC.

Check to see if your android application has the permission to use the internet (specified in the manifest: "USES_INTERNET" or something like that).

Also your python script discards the connection as soon as it is made.

In python change bind address to 0.0.0.0 . It will bind for all IPs attached to your machine. Then in android app change to correct IP of your computer.

IP 127.0.0.1 is a loopback and you can't connect to it from outside of the system.

The android phone doesn't know what PCName is, change "PCName" in the python code back to '127.0.0.1', then in the android project put in the local IP address of the server.

This of course assuming that both the phone and the server are on the same local network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM