Python(Server) Android(Client) Socket Programming

∥☆過路亽.° 提交于 2021-02-08 05:14:13

问题


I'd like to make a program which connects Python code with Android Studio. But there has been a problem on android studio which is not showing any UI that I'd like to show on Emulator Screen. I think it is due to "StrictMode". But If I except the StrictMode Code. The Program is stopped. What should I do? Here is the codes.

  1. Python Code(Server)

    import socket
    import random as r
    
    HOST = "localhost"
    PORT = 9999
    
    x = ['10', '20', '30', '40', '50']
    y = ['-10', '-20', '-30','-40', '-50']
    rssi = ['1.5', '2.5', '3.5', '4.5', '5.5']
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Socket created')
    
    try:
        s.bind((HOST, PORT))
    except socket.error as err:
        print('Bind failed. Error Code : ' .format(err))
    s.listen(10)
    print("Socket Listening")
    conn, addr = s.accept()
    while(True):
        i = r.randint(0, 4)
        conn.send(bytes("x : " + x[i] + " y : "+ y[i] + " rssi : " +                    
    rssi[i] + "\r\n", 'UTF-8'))
    print("Message sent in python")
        data = conn.recv(1024)
        print(data.decode(encoding='UTF-8'))
    
  2. Android Studio(Client) - AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.yangseungchan.socketwithpython">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
        <uses-permission android:name="android.permission.INTERNET" />
    </manifest>
    

3.Android Studio(Client) - MainActivity.java

    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.os.StrictMode;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;

    public class MainActivity extends AppCompatActivity {

        Button button;
        TextView textView;

        private Socket clientSocket;
        private BufferedReader socketIn;
        private PrintWriter socketOut;
        private int port = 9999;
        private final String ip = "222.99.99.14";
        private MyHandler myHandler;
        private MyThread myThread;

        static String text;

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

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            try{
                clientSocket = new Socket(ip, port);
                socketIn = new BufferedReader(new         InputStreamReader(clientSocket.getInputStream()));
                socketOut = new PrintWriter(clientSocket.getOutputStream(), true);
            }catch(Exception e){
                e.printStackTrace();
            }

    myHandler = new MyHandler();
    myThread = new MyThread();
    myThread.start();

    button = (Button)findViewById(R.id.button);
    textView = (TextView)findViewById(R.id.textView);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            /*socketPython.Datastack.printStack();
            textView.setText((String)SocketwithPython.Datastack.Peek(0));*/
            socketOut.println(123);
        }
    });
}

class MyThread extends Thread{
    @Override
    public void run() {
        while(true){
            try{
                System.out.println("Trying to read...");
                String data = socketIn.readLine(); 
                Message msg = myHandler.obtainMessage(); 
                msg.obj = data;
                myHandler.sendMessage(msg);
                System.out.println(data);
                socketOut.print("Try"+"\r\n");
                socketOut.flush();
                System.out.println("Message sent");
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

class MyHandler extends Handler {
    public void handleMessage(Message msg){
        textView.setText(msg.obj.toString());
    }
}

}

来源:https://stackoverflow.com/questions/51580668/pythonserver-androidclient-socket-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!