Jump to content

Echo server: Difference between revisions

no edit summary
No edit summary
Line 555:
}
}</lang>
 
This example will handle many connections
 
<lang d>
import std.stdio, std.socket;
 
void main()
{
ushort port = 7;
int backlog = 10;
int max_connections = 60;
enum BUFFER_SIZE = 16;
 
Socket listener = new TcpSocket;
assert(listener.isAlive);
listener.bind(new InternetAddress(port));
listener.listen(backlog);
debug writeln("Listening on port ", port);
SocketSet sset = new SocketSet(max_connections + 1); // Room for listener.
Socket[] sockets;
char[BUFFER_SIZE] buf;
 
for (;; sset.reset())
{
sset.add(listener);
foreach (Socket each; sockets)
sset.add(each);
 
// Update socket set with only those sockets that have data avaliable for reading.
// Options are for read, write, and error.
Socket.select(sset, null, null);
int i;
 
// Read the data from each socket remaining, and handle the request
for ( i = 0; ; ++i )
{
next:
if ( i == sockets.length )
break;
if ( sset.isSet(sockets[i]) )
{
int read = sockets[i].receive(buf);
if (Socket.ERROR == read)
{
debug writeln("Connection error.");
goto sock_down;
}
else if (0 == read)
{
debug
{
try
{
// if the connection closed due to an error, remoteAddress() could fail
writefln("Connection from %s closed.", sockets[i].remoteAddress().toString());
}
catch (SocketException)
{
writeln("Connection closed.");
}
}
sock_down:
sockets[i].close(); // Release socket resources now
// remove from socket from sockets, and id from threads
if (i != sockets.length - 1)
sockets[i] = sockets[sockets.length - 1];
sockets = sockets[0 .. sockets.length - 1];
debug writeln("\tTotal connections: ", sockets.length);
goto next; // -i- is still the next index
}
else
{
debug writefln("Received %d bytes from %s:\n-----\n%s\n-----",
read,
sockets[i].remoteAddress().toString(),
buf[0 .. read]);
sockets[i].send(buf[0 .. read]); // Echo what was sent
}
}
}
 
// connection request
if (sset.isSet(listener))
{
Socket sn;
try
{
if (sockets.length < max_connections)
{
sn = listener.accept();
debug writefln("Connection from %s established.", sn.remoteAddress().toString());
assert(sn.isAlive);
assert(listener.isAlive);
sockets ~= sn;
debug writefln("\tTotal connections: %d", sockets.length);
}
else
{
sn = listener.accept();
debug writefln("Rejected connection from %s; too many connections.", sn.remoteAddress().toString());
assert(sn.isAlive);
sn.close();
assert(!sn.isAlive);
assert(listener.isAlive);
}
}
catch (Exception e)
{
debug writefln("Error accepting: %s", e.toString());
if (sn)
sn.close();
}
}
}
}
</lang>
 
=={{header|Delphi}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.