1 /+ dub.json: 2 { 3 "authors": [ 4 "Dmitry Olshansky" 5 ], 6 "copyright": "Copyright © 2024, Dmitry Olshansky", 7 "dependencies": { 8 "photon": { "path": ".." } 9 }, 10 "description": "Echo server - a simple server that sends whatever it receives", 11 "license": "BOOST", 12 "name": "echo_server" 13 } 14 +/ 15 module echo_server; 16 17 import std.stdio; 18 import std.socket; 19 import std.conv; 20 import std.string; 21 import std.algorithm; 22 import std.conv; 23 import std.format; 24 import std.range; 25 26 import core.thread; 27 28 import photon; 29 import photon.support : logf; 30 31 // telnet localhost 1337 32 void server_worker(Socket client) { 33 ubyte[1024] buffer; 34 scope(exit) { 35 client.shutdown(SocketShutdown.BOTH); 36 client.close(); 37 } 38 logf("Started server_worker, client = %s", client); 39 for(;;) { 40 ptrdiff_t received = client.receive(buffer); 41 if (received < 0) { 42 perror("Error while reading from client"); 43 return; 44 } 45 else if (received == 0) { //socket is closed (eof) 46 return; 47 } 48 else { 49 logf("Server_worker received:\n<%s>", cast(char[])buffer[0.. received]); 50 } 51 ptrdiff_t sent; 52 do { 53 ptrdiff_t ret = client.send(buffer[sent .. received]); 54 if (ret < 0) { 55 perror("Error while writing to client"); 56 return; 57 } 58 sent += ret; 59 } while(sent < received); 60 } 61 } 62 63 void server() { 64 Socket server = new TcpSocket(); 65 server.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); 66 server.bind(new InternetAddress("127.0.0.1", 1337)); 67 server.listen(1000); 68 69 logf("Started server"); 70 void processClient(Socket client) { 71 go(() => server_worker(client)); 72 } 73 while(true) { 74 logf("Waiting for server.accept()"); 75 Socket client = server.accept(); 76 logf("New client accepted %s", client); 77 processClient(client); 78 } 79 } 80 81 void main() { 82 startloop(); 83 go(() => server()); 84 runFibers(); 85 }