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

Last change on this file since 167 was 142, checked in by alloc, 10 years ago

Fixes: Fixed #49

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