1 /** 2 Copyright: Copyright (c) 2014-2018 Andrey Penechko. 3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). 4 Authors: Andrey Penechko. 5 */ 6 7 module netlib.baseconnection; 8 9 import derelict.enet.enet; 10 import netlib; 11 import cbor; 12 13 mixin template BaseConnection() 14 { 15 bool isRunning; 16 17 // Local side of connection. 18 ENetHost* host; 19 20 ubyte[] buffer = new ubyte[1024*1024]; 21 22 void delegate(ref ENetEvent) connectHandler; 23 void delegate(ref ENetEvent) disconnectHandler; 24 25 void flush() 26 { 27 if (!isRunning) return; 28 enet_host_flush(host); 29 } 30 31 void stop() 32 { 33 isRunning = false; 34 enet_host_destroy(host); 35 } 36 37 void onConnect(ref ENetEvent event) 38 { 39 if (connectHandler) connectHandler(event); 40 } 41 42 void onPacketReceived(ref ENetEvent event) 43 { 44 ubyte[] packetData = event.packet.data[0..event.packet.dataLength]; 45 auto fullPacketData = packetData; 46 size_t packetId; 47 48 try 49 { 50 // decodes and pops ulong from range. 51 packetId = cast(size_t)decodeCborSingle!ulong(packetData); 52 53 handlePacket(packetId, packetData, event.peer); 54 } 55 catch(CborException e) 56 { 57 import std.conv : to; 58 error(e.to!string); 59 errorf("packet:%s length:%s data:%(%x%)", packetName(packetId), event.packet.dataLength, fullPacketData); 60 printCborStream(fullPacketData); 61 } 62 } 63 64 void onDisconnect(ref ENetEvent event) 65 { 66 if (disconnectHandler) disconnectHandler(event); 67 } 68 }