Monitor
Client.cs
Go to the documentation of this file.
1 using System;
2 using System.Net.Sockets;
3 using System.Text;
4 
5 namespace monitor
6 {
10  public static class Client
11  {
15  public const string defaultIP = "localhost";
16 
20  public const int defaultPort = 4500;
21 
25  private static TcpClient client = null;
26 
30  private static NetworkStream stream = null;
31 
35  private const int BufferMaxSize = 512;
36 
40  private static byte[] buffer = new byte[BufferMaxSize];
41 
46  private static byte[] receiveBuffer;
47 
48  private static int initialReceiveBufferIndex = 0;
49 
53  private static StringBuilder message = new StringBuilder();
54  private static int newLength = 1;
55  private static int packetCounter = 0;
56 
60  public delegate void ReadEvent(string msg, byte[] buffer);
61  public static ReadEvent readEvent = null;
62 
68  public static bool Open(string host)
69  {
70  return Client.Open(host, defaultPort);
71  }
72 
79  public static bool Open(string host, int port)
80  {
81  bool status = true;
82 
83  try
84  {
85  client = new TcpClient(host, port);
86 
87  stream = client.GetStream();
88 
89  // Start reading tcp stream and call "ReadCallback" method when newLength data
90  // will be received
91  // initially, "newLength" is equal to 1, so first call to ReadCallback
92  // will be done after reception of 1 byte.
93 
94  // received data are stored in buffer
95  // Next reading will be done in ReadCallback method
96  stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
97  }
98  catch (ArgumentNullException e)
99  {
100  Console.WriteLine("ArgumentNullException: " + e);
101  status = false;
102  }
103  catch (SocketException e)
104  {
105  Console.WriteLine("SocketException: " + e.ToString());
106  status = false;
107  }
108  catch (Exception e)
109  {
110  Console.WriteLine("Unknown Exception: " + e.ToString());
111  status = false;
112  }
113 
114  return status;
115  }
116 
120  public static void Close()
121  {
122  if (stream != null) stream.Close();
123  if (client != null) client.Close();
124  }
125 
130  private static void ReadCallback(IAsyncResult ar)
131  {
132  if (client.Connected)
133  {
134  int bytesRead;
135 
136  try
137  {
138  // Termintae read operation, and get number of byte stored in buffer
139  bytesRead = stream.EndRead(ar);
140  }
141  catch (ObjectDisposedException e)
142  {
143  Console.WriteLine("Connection to server dropped: " + e.ToString());
144  return;
145  }
146 
147  newLength = 1;
148 
149  // if number of byte read is not 0, concatenate string and buffer
150  if (bytesRead > 0)
151  {
152  packetCounter++;
153 
154  if (packetCounter >= 3)
155  {
156  //Console.WriteLine("Supplementary packet " + packetCounter);
157  }
158 
159  // Append new data to current string (expecting data are ascii)
160  message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
161 
162  // Similarly, append received bytes to current buffer
163  if (receiveBuffer == null) receiveBuffer = new byte[bytesRead];
164  else Array.Resize<byte>(ref receiveBuffer, initialReceiveBufferIndex + bytesRead); // resize currrent buffer
165 
166  System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead); // and add received data
167  initialReceiveBufferIndex = receiveBuffer.Length; // move last index of current buffer
168  }
169 
170  // if it remains received data, prepare for a new reading (get another buffer to append to current one)
171  if (client.Available > 0)
172  {
173  newLength = client.Available;
174  if (newLength > BufferMaxSize) newLength = BufferMaxSize;
175  else newLength = client.Available;
176  }
177  else
178  {
179  // no more data to read, buffer and string can be send to upper level
180  readEvent?.Invoke(message.ToString(), receiveBuffer);
181 
182  message.Clear();
183  receiveBuffer = null;
184  initialReceiveBufferIndex = 0;
185  packetCounter = 0;
186  }
187 
188  // Prepare for reading new data
189  stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
190  }
191  }
192 
198  public static void Write(string mes)
199  {
200  if (client.Connected)
201  {
202  byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
203 
204  stream.Write(writeBuffer, 0, mes.Length);
205  }
206  }
207  }
208 }
static byte [] buffer
Internal buffer used when reading data from server
Definition: Client.cs:40
static int packetCounter
Definition: Client.cs:55
static int initialReceiveBufferIndex
Definition: Client.cs:48
const int defaultPort
Default server port number
Definition: Client.cs:20
static TcpClient client
Tcp client object
Definition: Client.cs:25
static void Write(string mes)
Write a string to server
Definition: Client.cs:198
static byte [] receiveBuffer
buffer containing received message from TCP server Used to concatenate internal buffers into one ...
Definition: Client.cs:46
const int BufferMaxSize
Size of internal buffer used when reading data from server
Definition: Client.cs:35
static NetworkStream stream
Stream object used for communication
Definition: Client.cs:30
const string defaultIP
Default server name
Definition: Client.cs:15
delegate void ReadEvent(string msg, byte[] buffer)
Callback to send received message to upper level
static StringBuilder message
String containing received message from tcp server
Definition: Client.cs:53
static int newLength
Definition: Client.cs:54
static bool Open(string host, int port)
Open connection to server "host", with port number "port"
Definition: Client.cs:79
Definition: Client.cs:5
static bool Open(string host)
Open connection to server "host", on default port number.
Definition: Client.cs:68
Static class for TCP client
Definition: Client.cs:10
static void Close()
Close connection to server
Definition: Client.cs:120
static ReadEvent readEvent
Definition: Client.cs:61
static void ReadCallback(IAsyncResult ar)
Callback call by stream.BeginRead after reception of newLength data
Definition: Client.cs:130