我正在开发一个使用TCP协议与服务器通信的android客户端。除了从服务器接收数据外,一切都还可以。我现在知道的唯一方法是定期检查是否有东西要读,这是不好的。是否有任何监听器,回调或任何方式在客户端收到消息时获得通知,以便我可以运行一个方法来读取和处理它?</ p>
这是我的代码
class QTcpSocket implements Runnable {
private String ip="";
private int port;
private Socket socket;
private DataOutputStream dataOutputStream;
private DataInputStream dataInputStream;
public QTcpSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getIp() {
return this.ip;
}
public void setPort(int port) {
this.port = port;
}
public void run() {
try {
socket = new Socket(this.ip, this.port);
dataOutputStream = new DataOutputStream( socket.getOutputStream() );
dataInputStream = new DataInputStream(socket.getInputStream());
String response = dataInputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
try {
byte[] buffer= message.getBytes();
dataOutputStream.write(buffer,0,buffer.length);
}catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isClosed() {
return socket.isClosed();
}
}