Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import vibe.d;
- enum port = 1234;
- enum address = "127.0.0.1";
- shared static this()
- {
- auto serverTask = runTask({
- listenTCP(port, (con) {
- auto server = Server(con);
- server.start();
- }, address);
- });
- auto clientTask = runTask({
- auto con = connectTCP(address, port);
- auto client = Client(con);
- client.start();
- });
- serverTask.join();
- clientTask.join();
- }
- struct Server
- {
- mixin ConnectionRunner;
- private:
- void perform ()
- {
- dispatch(nextMessage());
- }
- string nextMessage ()
- {
- return cast(string) connection.readLine();
- }
- void dispatch (string message)
- {
- logInfo("Received message: '%s'", message);
- switch (message)
- {
- case Messages.stop: stop(); break;
- case Messages.foo: foo(); break;
- default: logInfo("Unrecognized message sent: '%s'", message);
- }
- }
- void foo ()
- {
- logInfo("This is foo");
- }
- }
- struct Client
- {
- mixin ConnectionRunner;
- private:
- void perform ()
- {
- writeLine("foo");
- sleep(500.msecs);
- }
- void writeLine (string message)
- {
- connection.write(message ~ "\r\n");
- }
- }
- private enum Messages
- {
- stop = "stop",
- foo = "foo"
- }
- template ConnectionRunner ()
- {
- private
- {
- bool isRunning;
- TCPConnection connection;
- }
- this (TCPConnection connection)
- {
- this.connection = connection;
- }
- void start ()
- {
- logInfo("Starting %s", name);
- isRunning = true;
- run();
- }
- private:
- void run ()
- {
- logInfo("Running %s", name);
- // while (isRunning && connection.connected)
- perform();
- }
- void stop ()
- {
- logInfo("Stopping %s", name);
- isRunning = false;
- if (connection.connected)
- connection.close();
- }
- string name ()
- {
- return typeid(typeof(this)).name;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement