Socket: Detect connection close
nrgyzer
nrgyzer at gmail.com
Sun Mar 23 13:12:36 PDT 2014
Hi guys,
I'm experimenting with sockets and having trouble to detect when
the remote side closes the connection. Here's my code:
// Client:
module client;
import std.socket;
void main()
{
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress("localhost", 8080));
SocketStream ss = new SocketStream(s);
for (int i= 0; i < 10; i++)
{
ss.write(1);
ss.flush();
}
ss.socket.shutdown(SocketShutdown.BOTH);
ss.close();
}
// Server:
module server;
import std.sdio;
import std.socket;
void main()
{
TcpSocket s = new TcpSocket(AddressFamily.INET);
s.bind(new InternetAddress("localhost", 8080));
s.blocking(false);
s.listen(0);
while(1)
{
try {
Socket requestSocket = oSocket.accept();
RequestThread rt = new RequestThread(requestSocket);
rt.start();
}
catch (SocketAcceptException e)
{
Thread.yield();
}
}
s.socket.shutdown(SocketShutdown.BOTH);
s.close();
}
class RequestThread : Thread
{
private {
__gshared Socket s;
void run()
{
ubyte[1] buffer;
while(s.isAlive)
{
s.receive(buffer);
writeln("receiving");
}
writeln("client closed connection");
}
}
public this(Socket socket)
{
super(&run);
s = socket;
}
}
I know... dirty (really) dirty code, but it works , except that
I'm in an endless loop and my server always prints "receiving". I
never see "client closed connection" although the client sends
only 10 int values. It seems that "s.isAlive" is always true. How
can I detect when the client closes the connection (or how can I
detect if the connection is broken)?
Thanks for any suggestions or ideas!
More information about the Digitalmars-d-learn
mailing list