I have an application in android that communicate to a server which is python throw socket connection. This is my doInBackground method in android:
protected String doInBackground(String... arg0) {
String username = arg0[0];
String result;
try {
///Socket Connection
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(username);
out.flush();
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = null;
while((line=br.readLine()) != null){
sb.append(line);
}
result = sb.toString();
socketResult = result;
isr.close();
br.close();
//socket.close();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
and this is a slice of my server side code which i send & recieve message and its Python:
def run(self):
i = True
while i:
strRecieved = self.sock.recv(self.recieveBuffer).decode('utf-8')
if strRecieved != "":
print('Client sent: ' + strRecieved)
msg = "yes"
self.sock.send(msg.encode('utf-8'))
print('Message sended to client: ' + msg)
strRecieved = ""
self.sock.close()
I defined a button and when i click on that button my AsyncTask class will execute. My application work fine if i just send one message to server and recieve one message from server but when i click on that button for second time, nothing will happen either on server and client. I don't know what should i do to send & recieve multiple messages with one socket connection. I will appriciate if you help me. Thanks.