C# detect TCP client disconnection -
i working on tcp multithread server c# window application form, , trying detect if machine of client shutdown , disconnects server. have read posts , have ideas:
how determine if tcp connected or not?
instantly detect client disconnection server socket
but i'm not sure call function isconnected
my code following:
public bindinglist<tablet> tabletlist = new bindinglist<tablet>(); private socket socket_server = null; private thread mythread = null; private socket socket_connect = null; private dictionary<string, socket> dic = new dictionary<string, socket> { }; private string remoteendpoint; socket_server = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); ipaddress serverip = ipaddress.parse("192.168.2.146"); ipendpoint point = new ipendpoint(serverip, portnum); socket_server.bind(point); socket_server.listen(50); mythread = new thread(listen_disp); mythread.isbackground = true; mythread.start(); console.writeline("server start"); private void listen_disp() { try { while (true) { //this not working (int = 0; < tabletlist.count; i++) { if (!socketconnected(dic[tabletlist[i].ip])) { console.writeline(remoteendpoint + "disconnected"); } } try { socket_connect = socket_server.accept(); remoteendpoint = socket_connect.remoteendpoint.tostring(); console.writeline(remoteendpoint + " connected"); dic.add(remoteendpoint, socket_connect); tablet newtablet = new tablet(); newtablet.ip = remoteendpoint; newtablet.status = "online"; tabletlist.add(newtablet); } catch (exception ex) { console.writeline(ex.tostring()); } } console.writeline("end of while"); } catch (exception ex) { console.writeline(ex.tostring()); } } static class socketextensions { public static bool isconnected(this socket socket) { try { return !(socket.poll(1, selectmode.selectread) && socket.available == 0); } catch (socketexception) { return false; } } }
thanks help.
there's lot of misinformation on subject, , of present in questions linked. reliable way detect tcp disconnection try write connection. read timeout can indicate dropped connection, may mean lot of other things too, such stuck server. eos condition when reading indicates graceful disconnect. isconnected() method , friends give history of have done socket: don't give current state of connection. can't, because, absent pending write request, there no state know. tcp doesn't maintain akin dial tone.
Comments
Post a Comment