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.