1

I write my own telnet client. And I have one problem and cannot to solve it. I connect to the device and communicate with it successfully, but in some moment device disconnect.

When I use Zoc terminal it write "[TELNET] INFO: DISCONNECTED" in this case.

When I use my own terminal I cannot to recognize this case. Property "Connected" in TcpClient is True. I will receive exception when I try to write something into stream after disconnection. But this is too late.

How I can recognize that connection lost?

Thanks.

nazar.kitsak
  • 70
  • 3
  • 8
  • 1
    please show relevant source code... – Yahia Oct 30 '13 at 15:56
  • var tcpSocket = new TcpClient( Host, Port ); tcpSocket.Connect( Host, Port ); var stream = tcpSocket.GetStream(); – nazar.kitsak Oct 30 '13 at 15:58
  • sorry but that is not the relevant part :-( – Yahia Oct 30 '13 at 15:59
  • I am read/write data in while loop. – nazar.kitsak Oct 30 '13 at 16:00
  • 1
    If you mean when a client initiates a disconnect on purpose then you should modify your protocol to send a disconnect message. If you mean when a client disconnects inadvertedly (like a power outage or IP address change) then the client has no means to communicate any longer. The connection will have to fail on server end via timeout/connection reset. – P.Brian.Mackey Oct 30 '13 at 16:02
  • Then you can only use the exception as indication of a lost connection... an alternative/better way to implement this is described in the answer below... – Yahia Oct 30 '13 at 16:03
  • I found solution [here](http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c) `bool SocketConnected(Socket s) { bool part1 = s.Poll(1000, SelectMode.SelectRead); bool part2 = (s.Available == 0); if (part1 & part2) return false; else return true; }` I call this code with some interval and know when connection lost. – nazar.kitsak Oct 31 '13 at 09:17

1 Answers1

0

Try using Socket instead of TcpClient. Some telnet daemons require each key press to flush the buffer, so try calling Stream.Flush on your relevant stream. I recommend tying a NetworkSteam to your Socket and wrapping it in a TextWriter and calling Flush on every key press.

With Socket you can recognize a lost connection by seeing that Socket.ReceiveAsync completes with success and zero bytes returned. You can also use the synchronous Socket.Receive and examine the exception that is thrown.

Michael J. Gray
  • 9,784
  • 6
  • 38
  • 67