diff --git a/src/main/protocol/HConnection.java b/src/main/protocol/HConnection.java index 73046ce..31c2b57 100644 --- a/src/main/protocol/HConnection.java +++ b/src/main/protocol/HConnection.java @@ -14,9 +14,48 @@ import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; public class HConnection { + + private volatile Queue sendToClientAsyncQueue = new PriorityQueue<>(); + private volatile Queue 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 { NOT_CONNECTED, PREPARING, // DOMAIN AND PORT BEEN PASSED @@ -386,18 +425,14 @@ public class HConnection { public boolean sendToServer(HPacket message) { if (outHandler == null) return false; outHandler.sendToStream(message.toBytes()); - return false; + return true; } public void sendToClientAsync(HPacket message) { - new Thread(() -> { - sendToClient(message); - }).start(); + sendToClientAsyncQueue.add(message); } public void sendToServerAsync(HPacket message) { - new Thread(() -> { - sendToServer(message); - }).start(); + sendToServerAsyncQueue.add(message); } }