我有一个使用我的自定义异步网络的 android 客户端,它运行良好,接收良好。但是,在某些时候,服务器几乎同时发送 2 条消息(服务器中有 2 个不同的线程)但是在客户端,当这种情况发生时,它只收到第一条消息,已经尝试使用 runnable,在解析时保持接收消息,但没有成功。如果有人可以帮助我,我该如何解决这个问题。
我的接收代码:
interface RecieveCallback {
void callback(int recievedBytes, InputStream stream);
}
public class Recieve implements Runnable {
private RecieveCallback callback;
private InputStream stream;
private byte[] buffer;
public Recieve(InputStream inStream, byte[] _buffer, RecieveCallback _callback) {
callback = _callback;
stream = inStream;
buffer = _buffer;
}
public void run() {
try {
while (true) {
final int recievedBytes = stream.read(buffer);
(new Runnable() {
public void run() {
callback.callback(recievedBytes, stream);
}
}).run();
}
} catch (IOException e) {
Log.e("Recieve", e.getMessage());
}
}
}
public Connection() {
this(host, port);
}
public Connection(String ip, int _port) {
inMessage = new NetworkMessage();
try {
serverAddres = InetAddress.getByName(ip);
socket = new Socket(serverAddres, _port);
socketOut = socket.getOutputStream();
} catch (IOException e) {
Log.e("Connect", e.getMessage());
}
}
public void Connect() {
try {
BeginRecieve(socket.getInputStream(), inMessage.getBuffer(), new RecieveCallback() {
public void callback(int recievedBytes, InputStream stream) {
OnRecieve(recievedBytes, stream);
}
});
} catch (IOException e) {
Log.e("BeginRecieve", e.getMessage());
}
}
public boolean EndRead(int recievedBytes, InputStream stream) {
int size = (int)inMessage.GetUInt32() + 4;
while (recievedBytes < size) {
try {
recievedBytes += stream.read(inMessage.getBuffer(), recievedBytes, (size - recievedBytes));
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
inMessage.setLength(size);
return true;
}
public void OnRecieve(int recievedBytes, InputStream stream) {
inMessage.setPosition(0);
if (!EndRead(recievedBytes, stream)) {
return;
}
NetworkMessage tempMessage = inMessage;
if (!ParseMessage(tempMessage)) {
//Tratar erro
}
}
public void BeginRecieve(InputStream inStream, byte[] _buffer, RecieveCallback _callback) {
if (beginRecieve != null && beginRecieve.isAlive()) {
beginRecieve.interrupt();
}
beginRecieve = new Thread(new Recieve(inStream, _buffer, _callback));
beginRecieve.start();
}