Advertisement
Guest User

Socket timeout test D

a guest
Mar 5th, 2015
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 2.09 KB | None | 0 0
  1. // main.d
  2. void main(string[] args) {
  3.     try {
  4.         import server;
  5.         handleServer();
  6.     }
  7.     catch { // being lazy, so when it can't bind, connect as client ...
  8.         import client;
  9.         handleClient();
  10.     }
  11.    
  12.     import std.stdio : readln;
  13.     readln();
  14. }
  15. // server.d
  16. module server;
  17.  
  18. import std.socket;
  19. import core.thread;
  20.  
  21. void handleServer() {
  22.     Socket ssoc = new TcpSocket();
  23.     ssoc.bind(new InternetAddress("127.0.0.1", 8989));
  24.     ssoc.listen(100);
  25.    
  26.     auto csoc = ssoc.accept();
  27.     // if we sleep here it will be a success too
  28.     // I assume that's because the time-out isn't expected till one or more bytes have been received
  29.     // by the client.
  30.     // It's safe to assume that time-outs are not related to disconnection as it will
  31.     // most likely assume the connection to still be established ???
  32.     ubyte[] buf = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  33.     csoc.send(buf[0 .. $/2]); // Sending first portion of 5 bytes (client is expecting 10)
  34.     Thread.sleep(dur!("seconds")(10)); // waits 10 seconds between sending the last portion
  35.     csoc.send(buf[$/2 .. $]); // Sending last portion of 5 bytes (the client should have a success by this time, so this is ignored completely)
  36. }
  37. // client.d
  38. module client;
  39.  
  40. import std.stdio : writefln;
  41. import std.socket;
  42. import std.datetime;
  43. import core.thread;
  44.  
  45. void handleClient() {
  46.     Socket csoc = new TcpSocket();
  47.     csoc.setOption(SocketOptionLevel.SOCKET,SocketOption.RCVTIMEO, dur!("seconds")(5));
  48.     StopWatch sw;
  49.     csoc.connect(new InternetAddress("127.0.0.1", 8989));
  50.     writefln("Connected...");
  51.     sw.start(); // starts a stop watch to track time
  52.  
  53.     auto buf = new ubyte[10]; // The buffer for receiving 10 byte
  54.     csoc.receive(buf); // Receives the buffer (however only the portion of 5 bytes should be received. No time-out either
  55.     sw.stop(); // Stops the stop watch
  56.    
  57.     // Gathers information
  58.     writefln("Socket Error Text: '%s'", csoc.getErrorText);
  59.     writefln("Time: '%s'", sw.peek().msecs);
  60.     writefln("Buffer: %s", buf); // Only the first portion of 5 bytes is displaying.
  61.     // I assume time-out's are triggered by the socket core and not the program itself by the server sleeping etc.
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement