Java客户端和python服务器连接

时间:2017-11-16 16:30:58

标签: java android python android-studio networking

我正在android studio中开发一个应用程序而且我需要每当我​​点击一个特定的按钮时它会在java客户端和python服务器之间创建一个连接。
如果手机中有wifi连接,我首先检查当你进入特定按钮的页面\活动时 它工作正常。然后我试着这样做,它没有工作(重要的是说当前的代码使我的手机和我的应用程序崩溃并停止)
简单的服务器:

HOST = '192.168.1.21'
PORT = 9000


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    client_socket, client_address = server_socket.accept()
    print 'Connect with ' + client_address[0]
    data = client_socket.recv(1024)
    print "data :"
    print data
    print " end"
    if data == HOST+"/n":
        print 'hi'
    else:
        i = 0
        while i < 15:
            print i
            i += 1
    client_socket.close()
    server_socket.close()
if __name__ == '__main__':
    main()

这只是检查连接。由于if中的主机+ / n,它可能看起来很奇怪。我最近因为我是java新手并且不知道如何发送数据而对其进行了修改。但这不是问题。

public void ButtonClicked(View view) {
        EditText editText = findViewById(R.id.edit_text);
        final String ip = editText.getText().toString();
        Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
        try {
            InetAddress host = InetAddress.getByName(ip);
            final Client client = new Client(host, 9000);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        client.send(ip);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            client.send(ip);
        }
        catch (IOException e) {
            System.out.println("Caught Exception: " + e.toString());
        }

我在android studio 3.0中读到你需要在发送数据时创建一个线程。 你在这里看到的客户类:

public class Client
{
    private Socket socket = null;
    private BufferedReader reader = null;
    private BufferedWriter writer = null;

    public Client(InetAddress address, int port) throws IOException
    {
        socket = new Socket(address, port);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void send(String msg) throws IOException
    {
        writer.write(msg, 0, msg.length());
        writer.flush();
    }

    public String recv() throws IOException
    {
        return reader.readLine();
    }

}

它可能只是一个简单的事情,我不知道但这些是代码,我无法连接到服务器。我发现服务器工作正常,因为如果我从手机连接到网络上的192.168.1.21我收到连接,它确实很少。 ty的帮助 - 我想得到最简单的修复,因为我是java的新手。
(对不起,如果那里有语法\拼写错误)

编辑崩溃的logcat
enter image description here

1 个答案:

答案 0 :(得分:0)

在日志结尾处显示NetworkOnMainThread。在你的代码中,在你的单独线程下面有一行client.send(ip),它在主线程上执行。

相关问题