2020-09-29 17:13:36 +00:00
|
|
|
module tristanable.watcher;
|
2020-09-29 09:57:25 +00:00
|
|
|
|
|
|
|
public final class Watcher : Thread
|
|
|
|
{
|
2020-09-29 17:13:36 +00:00
|
|
|
/* The manager */
|
|
|
|
private Manager manager;
|
|
|
|
|
|
|
|
/* The socket to read from */
|
|
|
|
private Socket socket;
|
|
|
|
|
|
|
|
this(Manager manager, Socket endpoint)
|
2020-09-29 09:57:25 +00:00
|
|
|
{
|
2020-09-29 17:13:36 +00:00
|
|
|
super(&run);
|
|
|
|
this.manager = manager;
|
|
|
|
socket = endpoint;
|
2020-09-29 09:57:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private void run()
|
|
|
|
{
|
|
|
|
/* Continuously dequeue tristanable packets from socket */
|
|
|
|
while(true)
|
|
|
|
{
|
|
|
|
/* Receive payload (tag+data) */
|
|
|
|
byte[] receivedPayload;
|
|
|
|
|
|
|
|
/* Block for socket response */
|
|
|
|
bool recvStatus = receiveMessage(endpoint, receivedPayload);
|
|
|
|
|
|
|
|
/* If the receive was successful */
|
|
|
|
if(recvStatus)
|
|
|
|
{
|
|
|
|
/* Decode the ttag-encoded message */
|
|
|
|
DataMessage message = DataMessage.decode(receivedPayload);
|
|
|
|
|
2020-09-29 17:13:36 +00:00
|
|
|
/* TODO: Remove isTag, improve later, oneshot */
|
|
|
|
|
|
|
|
/* The matching queue (if any) */
|
|
|
|
Queue queue = manager.getQueue(message.getTag());
|
|
|
|
|
|
|
|
/* If the tag belongs to a queue */
|
|
|
|
if(queue)
|
|
|
|
{
|
|
|
|
/* Add an item to this queue */
|
|
|
|
queue.enqueue(new QueueItem(message.getData()));
|
|
|
|
}
|
|
|
|
/* If the tag is unknwon */
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* TODO: Add to dropped queue? */
|
2020-09-29 09:57:25 +00:00
|
|
|
|
2020-09-29 17:13:36 +00:00
|
|
|
/* Do nothing */
|
|
|
|
}
|
2020-09-29 09:57:25 +00:00
|
|
|
}
|
|
|
|
/* If the receive failed */
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* TODO: Stop everything */
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Like in `dequeue` we don't want the possibility
|
|
|
|
* of racing back to the top of the loop and locking
|
|
|
|
* the mutex again right before a thread switch,
|
|
|
|
* so we make sure that a switch occurs to a different
|
|
|
|
* thread
|
|
|
|
*/
|
|
|
|
Thread.getThis().yield();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|