简体   繁体   English

Sockets 从 Java 到 Python 并再次返回

[英]Sockets from Java to Python and back again

Is it possible to communicate with a Raspberry Pi from an Android phone through an app?是否可以通过应用程序从 Android 手机与 Raspberry Pi 进行通信? I've tried and succeded in sending information form the Android App to the RaspberryPi.我已经尝试并成功地将信息从 Android 应用程序发送到 RaspberryPi。 But when I try to connect to the phone from the RPi by calling phoneServer.connect(addr) , python just times out.但是当我尝试通过调用phoneServer.connect(addr)从 RPi 连接到手机时,python 只是超时。 So is it possible to send a command from the Python Socket to the Java Socket?那么是否可以从 Python Socket 向 Java Socket 发送命令?

Initialy I had one socket in the python script and I just used tcpCliSock.sendto(data.encode(),addr) to try and send the command to the java socket, but that resulted in a broken pipe errer (32), so I thought I might be able to fix it by creating a new socket, but it hasn't fixed the issue. Initialy I had one socket in the python script and I just used tcpCliSock.sendto(data.encode(),addr) to try and send the command to the java socket, but that resulted in a broken pipe errer (32), so I以为我可以通过创建一个新的套接字来解决它,但它并没有解决这个问题。

I've currently tried setting up sockets in Python and in Java.我目前尝试在 Python 和 Java 中设置 sockets。 The ones in Python (on RPi) looks something like this: Python(在 RPi 上)中的那些看起来像这样:

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

PORTSEND = 7801
while True:
    print('Waiting for connection')
    tcpCliSock,addr = tcpSerSock.accept()
    data = ''
    print('...connected from :', addr)
    try:
        while True:
            d = tcpCliSock.recv(BUFSIZE)
            data = data + d.decode("utf-8")
            print(data)    
            if data == 'XButton':
                print('XButton Pressed')
                lst = list(addr)
                lst[1] = PORTSEND
                addr = tuple(lst)
                phoneServer = socket(AF_INET, SOCK_STREAM)
                phoneServer.connect(addr)
                phoneServer.send(data.encode())
                phoneServer.close()
                break
            else:
                if not d:
                    break
    except KeyboardInterrupt:
        print('keyboard pressed')

tcpSerSock.close()

And the ones in Java (on the Android) looks something like this: Java(在 Android 上)中的那些看起来像这样:

public class MainActivity extends AppCompatActivity  {
    EditText iPField;
    Button xButton;
    public static String wifiModuleIp = "";
    public static int wifiModulePort = 0;
    public static String CMD = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread myThread = new Thread(new MyServerThread());
        myThread.start();

        iPField = (EditText) findViewById(R.id.IPEditField);
        xButton = (Button) findViewById(R.id.XButton);

        xButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "XButton";
                Socket_AsyncTask cmd_verify = new Socket_AsyncTask();
                cmd_verify.execute();
            }
        });

    public void getIPandPort()
    {
        String iPandPort = iPField.getText().toString();
        Log.d("MYTEST","IP String: "+ iPandPort);
        String temp[]= iPandPort.split(":");
        wifiModuleIp = temp[0];
        wifiModulePort = Integer.valueOf(temp[1]);
        Log.d("MY TEST","IP:" +wifiModuleIp);
        Log.d("MY TEST","PORT:"+wifiModulePort);
    }
    public class Socket_AsyncTask extends AsyncTask<Void,Void,Void>
    {
        Socket socket;

        @Override
        protected Void doInBackground(Void... params){
            try{
                InetAddress inetAddress = InetAddress.getByName(MainActivity.wifiModuleIp);
                socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeBytes(CMD);
                dataOutputStream.close();
                socket.close();
            }catch (UnknownHostException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}
            return null;
        }
    }

    class MyServerThread implements Runnable
    {
        Socket s;
        ServerSocket ss;
        InputStreamReader isr;
        BufferedReader bufferedReader;
        String message;
        Handler h = new Handler();

        @Override
        public void run() {
            try
            {
                ss = new ServerSocket(7801);
                while(true)
                {
                    s = ss.accept();
                    isr = new InputStreamReader(s.getInputStream());
                    bufferedReader = new BufferedReader(isr);
                    message = bufferedReader.readLine();

                    h.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
                        }
                    });

                }

            }catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

I use for such tasks ready libraries for html retrieve.我使用用于 html 检索的此类任务准备库。

For example, on Android exists org.apache.http.client (now they recommend newer library, but old still works well).例如,在 Android 上存在 org.apache.http.client (现在他们推荐更新的库,但旧的仍然可以正常工作)。 And Python also have http client in standard library https://docs.python.org/3/library/http.client.html And Python also have http client in standard library https://docs.python.org/3/library/http.client.html

It is convenient and save lot of time, REusing some ready code for general tasks.它既方便又节省大量时间,为一般任务重用一些现成的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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