Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio;
- import std.socket;
- import std.conv;
- import core.thread;
- /**
- This example shows how to realize a network server without threading.
- Instead of Threads we use Fibers as a replacement, to not block our running Fibers
- the Sockets need to be run in non-blocking mode.
- **/
- // worker fiber for each client
- // waits for data and prints it out
- class ClientFiber : Fiber {
- private Socket sock;
- this(Socket s) {
- this.sock = s;
- super(&run);
- }
- private void run() {
- while(true) {
- // receive and show data as a string
- byte[1024] buf;
- int len = sock.receive(buf);
- if(len > 0) {
- string s = (cast(immutable(char)*)buf)[0..len];
- writeln(s);
- }
- Fiber.yield(); // return to the caller
- // when the fiber is called again, we continue here
- }
- }
- }
- void main(string[] args)
- {
- if(args.length == 1) // if we provide no args run a server
- {
- // create a socket that accepts new connections
- // INET is using IP4, STREAM is a TCP connection
- auto listener = new Socket(AddressFamily.INET, SocketType.STREAM);
- listener.blocking(false);
- listener.bind(new InternetAddress(2525));
- listener.listen(10);
- // stores all fibers that need to be run
- Fiber[] fibers;
- // listener for new connections
- void listen() {
- writeln("listen");
- Socket newclient;
- while(listener.isAlive()) {
- newclient = listener.accept();
- if(!wouldHaveBlocked()) {
- Fiber clientfiber = new ClientFiber(newclient);
- fibers ~= clientfiber;
- writeln(fibers.length);
- }
- Fiber.yield();
- }
- }
- // register the listener fiber
- Fiber listenFiber = new Fiber(&listen);
- fibers ~= listenFiber;
- // main loop of the program - runs all fibers
- while(true) {
- foreach(f; fibers) {
- f.call();
- }
- Thread.sleep(100.msecs); // to not eat up all your cpu
- }
- }
- else // if the program is run with an argument start a client
- {
- // connect to the server socket
- auto sock = new Socket(AddressFamily.INET, SocketType.STREAM);
- sock.connect(new InternetAddress("127.0.0.1", 2525));
- // send some data
- sock.send("foo!");
- Thread.sleep(4*1_000.msecs);
- sock.send("bar");
- Thread.sleep(100.msecs);
- // experiment with receiving on the client side
- /*while(true) {
- byte[1024] buf;
- int len = sock.receive(buf);
- if(len > 0) {
- string s = (cast(immutable(char)*)buf)[0..len];
- writeln(s);
- }
- }*/
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement