using System; using System.Net; using System.Net.Sockets; namespace AllocsFixes.NetConnections.Servers.Telnet { public class TelnetConnection : IConnection { private bool authenticated = false; private bool authEnabled; private TcpClient client; private NetworkStream stream; private string lineBuffer = string.Empty; private EndPoint endpoint; public TelnetConnection (TcpClient client, bool authEnabled) { this.authEnabled = authEnabled; this.client = client; this.stream = client.GetStream (); this.endpoint = client.Client.RemoteEndPoint; } public EndPoint GetEndPoint () { return endpoint; } private void WriteByte (byte v) { if (!IsClosed () && stream.CanWrite) { stream.WriteByte (v); } } public void WriteLine (string s) { try { if (!IsClosed () && stream.CanWrite) { for (int i = 0; i < s.Length; i++) { WriteByte ((byte)s [i]); } WriteByte (13); WriteByte (10); } } catch (Exception e) { Log.Out ("Error writing to client: " + e); } } public void Close () { if (client != null) client.Close (); client = null; } public bool IsClosed () { if (client != null && !client.Connected) { Log.Out ("Telnet connection interrupted: " + endpoint); } return (client == null) || (!client.Connected); } public bool IsAuthenticated () { return !authEnabled || authenticated; } public void SetAuthenticated () { authenticated = true; } public bool Read () { while (!IsClosed() && stream.CanRead && stream.DataAvailable) { int b = stream.ReadByte (); if (b == '\r' || b == '\n') { if (lineBuffer.Length > 0) return true; } else { lineBuffer += (char)b; } } return false; } public string GetLine () { string res = lineBuffer; lineBuffer = string.Empty; return res; } } }