我在android中有一个应用程序,它与一个python throw socket连接的服务器进行通信。这是我在android中的doInBackground方法:
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());
}
}
这是我发送的一段服务器端代码&收到消息及其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()
我定义了一个按钮,当我点击该按钮时,我的AsyncTask类将会执行。如果我只是向服务器发送一条消息并从服务器收到一条消息,但是当我第二次点击该按钮时,我的应用程序工作正常,服务器和客户端都不会发生任何事情。我不知道该怎么办才能发送&通过一个套接字连接接收多条消息。如果你帮助我,我会恭喜你。感谢。