digitalmars.D.learn - How can I set Timeout of Socket?
- Marcone (4/4) Nov 14 2020 Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
- FreeSlave (23/27) Nov 14 2020 Perhaps using Socket.select and SocketSet?
- Anonymouse (29/33) Nov 15 2020 My program does something like this. (untested)
Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.connect(new InternetAddress("domain.com", 80));
I want that program raise an error if reach for example 30
seconds of timeout.
Nov 14 2020
On Sunday, 15 November 2020 at 00:05:08 UTC, Marcone wrote:
Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.connect(new InternetAddress("domain.com", 80));
I want that program raise an error if reach for example 30
seconds of timeout.
Perhaps using Socket.select and SocketSet?
import std.socket;
import std.stdio;
import core.time;
void main()
{
Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.blocking = false;
auto set = new SocketSet(1);
set.add(s);
s.connect(new InternetAddress("dlang.org", 80));
scope(exit) s.close();
Socket.select(null, set, null, dur!"seconds"(10));
if (set.isSet(s))
{
writeln("socket is ready");
}
else
{
writeln("could not connect");
}
}
Nov 14 2020
On Sunday, 15 November 2020 at 00:05:08 UTC, Marcone wrote:
Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.connect(new InternetAddress("domain.com", 80));
I want that program raise an error if reach for example 30
seconds of timeout.
My program does something like this. (untested)
Socket s = new TcpSocket;
s.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO,
30.seconds);
s.setOption(SocketOptionLevel.SOCKET, SocketOption.SNDTIMEO,
30.seconds);
auto addresses = getAddress("domain.com", 80);
bool isConnected;
foreach (address; addresses)
{
try
{
s.connect(address);
isConnected = true;
break;
}
catch (SocketException e)
{
// Failed, try next address
writeln(e.msg);
}
}
if (!isConnected) return false; // failed to connect
// Connected
You can tell whether a read timed out by looking at the amount of
bytes read (when `Socket.receive` returns `Socket.ERROR`) and the
value of `std.socket.lastSocketError` (and/or
`core.stdc.errno.errno` equaling EAGAIN).
Nov 15 2020









FreeSlave <freeslave93 gmail.com> 