Как мне подключить сервер python к проекту android? - PullRequest
0 голосов
/ 26 апреля 2020

Я работаю над проектом в Android Studio и хочу подключить его к серверу, который я написал в python, используя многопоточные сокеты. Сервер Python отлично работает с клиентами, написанными на python, но мой клиент Android не может подключиться. Это сервер:

# thread function
def threaded(soc):
    while True:

        # data received from client
        data = soc.recv(1024)
        if not data:
            print('Bye')


            break
       # todo
    # connection closed
    soc.close()


def main():
    host = 'localhost'

    port = 12345
    listen_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_soc.bind((host, port))
    print("socket binded to port", port)

    # put the socket into listening mode
    listen_soc.listen(5)
    print("socket is listening")

    # a forever loop until client wants to exit
    while True:

        # establish connection with client
        soc, addr = listen_soc.accept()
        print('Connected to :', addr[0], ':', addr[1])

        # Start a new thread and return its identifier
        start_new_thread(threaded, (soc,))
    listen_soc.close()


if __name__ == '__main__':
    main()

, а это клиент android:

private ServerHandler sh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sh = new ServerHandler();
        if(sh.connect("___.___.__.__", 12345))
            Log.d("MYTAG", "connected");
        else
            Log.d("MYTAG", "couldn't connect");
    }

Класс ServerHandler:

    public class ServerHandler extends Thread {
    private Socket socket;
    private BufferedReader in;
    private PrintStream out;
    public ServerHandler() {
        socket = new Socket();
    }

    /**
     * Tries to connect to a server
     * @return True if successfully connected, otherwise False
     */
    public boolean connect(String ip, int port) {
        try {
            socket.connect(new InetSocketAddress(ip, port));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintStream(socket.getOutputStream(), true /* If this is false, you need to call out.flush() for the PrintWriter to send*/);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Closes the socket
     */
    public void disconnect() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
        Sends a string *without* a \n
     */
    public void send(String s) {
        out.print(s);
    }
    /*
        Sends a string with a \n
     */
    public void sendLine(String s) {
        out.println(s);
    }
    /*
        Receives a line. NOTE: This method will lock the program until a **line** (\n) is received.
     */
    public String recvLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...