Skip to content

Instantly share code, notes, and snippets.

@lega911
Created October 11, 2015 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lega911/e103f22ead5aa9bb4699 to your computer and use it in GitHub Desktop.
Save lega911/e103f22ead5aa9bb4699 to your computer and use it in GitHub Desktop.
import vibe.d;
import core.time;
import std.stdio;
TCPConnection[] workers;
bool logging;
shared static this()
{
logging = false;
runTask({
writeln("Start worker connector");
listenTCP_s(8011, &worker_handler);
});
writeln("Start client connector");
listenTCP_s(8010, &handler);
}
struct Block {
ubyte code;
uint size;
ubyte[] buf;
}
uint readBlock(TCPConnection conn, Block *block) {
ubyte[4] buf;
if(!conn.waitForData(dur!"seconds"(100L))) {
writeln("Read head timeout");
return 1;
}
conn.read(buf);
block.code = buf[0];
block.size = buf[1] + (buf[2] << 8) + (buf[3] << 16);
block.buf = new ubyte[block.size];
if(!conn.waitForData(dur!"seconds"(100L))) {
writeln("Read body timeout");
return 1;
}
conn.read(block.buf);
return 0;
};
uint writeBlock(TCPConnection conn, Block *block) {
ubyte[4] head;
uint size = block.size;
head[0] = block.code;
head[1] = size & 0xff;
head[2] = (size & 0xff00) >> 8;
head[3] = (size & 0xff0000) >> 16;
conn.write(head);
conn.write(block.buf);
return 0;
}
void worker_handler(TCPConnection conn) {
writeln("Worker connected");
Block block;
if(readBlock(conn, &block)) return;
workers ~= conn;
while(conn.connected){
sleep(500.msecs);
}
writeln("Worker disconected");
}
void handler(TCPConnection conn) {
writeln("Client connected");
TCPConnection worker;
while(conn.connected){
Block req;
if(logging) { writeln("Read client"); }
if(readBlock(conn, &req)) return;
req.code = 15;
if(logging) { writeln(1, workers); }
// wait worker
while(workers.length == 0) {
sleep(1.msecs);
}
worker = workers[$-1];
workers.length -= 1;
if(logging) { writeln(2, workers); }
if(logging) { writeln("Write worker"); }
writeBlock(worker, &req);
if(logging) { writeln("read worker"); }
Block resp;
if(readBlock(worker, &resp)) {
writeln("Error read worker");
return;
}
workers ~= worker; // send worker to queue
if(logging) { writeln("Write client"); }
writeBlock(conn, &resp);
if(logging) { writeln("loop end"); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment