首页 > 解决方案 > 如何将 python 服务器连接到 android 项目?

问题描述

我正在 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()

这是安卓客户端:

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");
    }

服务器处理程序类:

    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;
        }
    }
}

标签: javapythonandroidsockets

解决方案


推荐阅读