source: binary-improvements/7dtd-server-fixes/src/NetConnections/Servers/Telnet/TelnetConnection.cs@ 180

Last change on this file since 180 was 174, checked in by alloc, 10 years ago

fixes

File size: 2.0 KB
Line 
1using System;
2using System.Net;
3using System.Net.Sockets;
4using System.Text;
5
6namespace AllocsFixes.NetConnections.Servers.Telnet
7{
8 public class TelnetConnection : IConnection
9 {
10 private bool authenticated = false;
11 private bool authEnabled;
12 private TcpClient client;
13 private NetworkStream stream;
14 private int lineBufferLength = 0;
15 private byte[] lineBuffer = new byte[200];
16 private EndPoint endpoint;
17
18 public TelnetConnection (TcpClient client, bool authEnabled)
19 {
20 this.authEnabled = authEnabled;
21 this.client = client;
22 this.stream = client.GetStream ();
23 this.endpoint = client.Client.RemoteEndPoint;
24 }
25
26 public EndPoint GetEndPoint ()
27 {
28 return endpoint;
29 }
30
31 private void WriteByte (byte v)
32 {
33 if (!IsClosed () && stream.CanWrite) {
34 stream.WriteByte (v);
35 }
36 }
37
38 public void WriteLine (string s)
39 {
40 try {
41 if (!IsClosed () && stream.CanWrite) {
42 byte[] utfData = Encoding.UTF8.GetBytes (s);
43 stream.Write (utfData, 0, utfData.Length);
44 WriteByte (13);
45 WriteByte (10);
46 }
47 } catch (Exception e) {
48 Log.Out ("Error writing to client: " + e);
49 }
50 }
51
52 public void Close ()
53 {
54 if (client != null)
55 client.Close ();
56 client = null;
57 }
58
59 public bool IsClosed ()
60 {
61 if (client != null && !client.Connected) {
62 Log.Out ("Telnet connection interrupted: " + endpoint);
63 }
64 return (client == null) || (!client.Connected);
65 }
66
67 public bool IsAuthenticated ()
68 {
69 return !authEnabled || authenticated;
70 }
71
72 public void SetAuthenticated ()
73 {
74 authenticated = true;
75 }
76
77 public bool Read ()
78 {
79 while (!IsClosed() && stream.CanRead && stream.DataAvailable) {
80 int b = stream.ReadByte ();
81 if (b == '\r' || b == '\n') {
82 if (lineBufferLength > 0) {
83 return true;
84 }
85 } else if (b >= 0) {
86 lineBuffer [lineBufferLength] = (byte)b;
87 lineBufferLength++;
88 }
89 }
90 return false;
91 }
92
93 public string GetLine ()
94 {
95 string res = Encoding.UTF8.GetString (lineBuffer, 0, lineBufferLength);
96 lineBufferLength = 0;
97 return res;
98 }
99
100 }
101}
Note: See TracBrowser for help on using the repository browser.