better async packetsending implementation

This commit is contained in:
sirjonasxx 2018-06-13 23:44:47 +02:00
parent 3970482ac7
commit 684a30be3e

View File

@ -14,9 +14,48 @@ import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
public class HConnection { public class HConnection {
private volatile Queue<HPacket> sendToClientAsyncQueue = new PriorityQueue<>();
private volatile Queue<HPacket> sendToServerAsyncQueue = new PriorityQueue<>();
public HConnection() {
new Thread(() -> {
while (true) {
if (inHandler != null) {
HPacket packet;
while ((packet = sendToClientAsyncQueue.poll()) != null) {
sendToClient(packet);
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
while (true) {
if (outHandler != null) {
HPacket packet;
while ((packet = sendToServerAsyncQueue.poll()) != null) {
sendToServer(packet);
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public enum State { public enum State {
NOT_CONNECTED, NOT_CONNECTED,
PREPARING, // DOMAIN AND PORT BEEN PASSED PREPARING, // DOMAIN AND PORT BEEN PASSED
@ -386,18 +425,14 @@ public class HConnection {
public boolean sendToServer(HPacket message) { public boolean sendToServer(HPacket message) {
if (outHandler == null) return false; if (outHandler == null) return false;
outHandler.sendToStream(message.toBytes()); outHandler.sendToStream(message.toBytes());
return false; return true;
} }
public void sendToClientAsync(HPacket message) { public void sendToClientAsync(HPacket message) {
new Thread(() -> { sendToClientAsyncQueue.add(message);
sendToClient(message);
}).start();
} }
public void sendToServerAsync(HPacket message) { public void sendToServerAsync(HPacket message) {
new Thread(() -> { sendToServerAsyncQueue.add(message);
sendToServer(message);
}).start();
} }
} }