Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection between Python Server and Android Application

This is my first question. I have looked for solutions of similar problems but in every case there were some differences comparing to my case. I am trying to establish a simple connection between a Python server and an Android application using sockets. The Android app starts a conversation with the server: it sends a message to the server, the server receives and displays it, then the server sends a reply to the app. The app displays the reply on the screen in a TextView. This is my code on the client side:

public class MyClient extends Activity implements OnClickListener{
EditText enterMessage;
Button sendbutton;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myclient);
    enterMessage = (EditText)findViewById(R.id.enterMessage);
    sendbutton = (Button)findViewById(R.id.sendbutton);
    sendbutton.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {
    Thread t = new Thread(){

        @Override
        public void run() {
            try {
                Socket s = new Socket("192.168.183.1", 7000);
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                dos.writeUTF(enterMessage.getText().toString());

                //read input stream
                DataInputStream dis2 = new DataInputStream(s.getInputStream());
                InputStreamReader disR2 = new InputStreamReader(dis2);
                BufferedReader br = new BufferedReader(disR2);//create a BufferReader object for input

                //print the input to the application screen
                final TextView receivedMsg = (TextView) findViewById(R.id.textView2);
                receivedMsg.setText(br.toString());

                dis2.close();
                s.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
    Toast.makeText(this, "The message has been sent", Toast.LENGTH_SHORT).show();
}   }

And on the server side this is my code:

from socket import *

HOST = "192.168.183.1" #local host
PORT = 7000 #open port 7000 for connection
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1) #how many connections can it receive at one time
conn, addr = s.accept() #accept the connection
print "Connected by: " , addr #print the address of the person connected
while True:
    data = conn.recv(1024) #how many bytes of data will the server receive
    print "Received: ", repr(data)
    reply = raw_input("Reply: ") #server's reply to the client
    conn.sendall(reply)
conn.close()

When I try to send a message from the app to the server it works perfectly. However, as soon as the server receives the message and displays it, the app immediately stops with the error message: has stopped unexpectedly. Please try again. Additional info: I am using adt-bundle for Android development and IDLE to run the server code. Both on Windows8.

like image 659
shallawati Avatar asked Apr 07 '14 10:04

shallawati


People also ask

Can we integrate Python with Android?

We can use python for web development, app development, analysis and computation of scientific and numeric data and software development. Following are some of the platforms for Python Android Development: QPython. PySide.

How does Python work on Android?

python-for-android is an open source build tool to let you package Python code into standalone android APKs. These can be passed around, installed, or uploaded to marketplaces such as the Play Store just like any other Android app.


1 Answers

From what I understand you use a thread in order to call the server but in the same thread you try to post back results to the UI.

final TextView receivedMsg = (TextView) findViewById(R.id.textView2); receivedMsg.setText(br.toString());

If you use your own Java thread you have to handle the following requirements in your own code: Synchronization with the main thread if you post back results to the user interface. I dont see that you are doing this.You either have to use a Handler or maybe you should consider using the Asynctask of android. With the AsyncTAsk you can write in the UI after this method is triggered. onPostExecute(Result) Invoked on the UI thread after the background computation finishes.

So inside this method you can write in the UI. have a look at these links http://learningdot.diandian.com/post/2014-01-02/40060635109 Asynctask vs Thread in android

like image 196
Periklis Douvitsas Avatar answered Nov 01 '22 22:11

Periklis Douvitsas