| Monitor

Client.cs
Go to the documentation of this file.
1 //
2 // Client.cs
3 //
4 // Author:
5 // Di MERCURIO Sébastien <dimercur@insa-toulouse.fr>
6 //
7 // Copyright (c) 2018 INSA - DGEI
8 //
9 // This program is free software: you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation, either version 3 of the License, or
12 // (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 using System;
23 using System.Net.Sockets;
24 using System.Text;
25
26 namespace monitor
27 {
31 public static class Client
32 {
36 public const string defaultIP = "localhost";
37
41 public const int defaultPort = 4500;
42
46 private static TcpClient client = null;
47
51 private static NetworkStream stream = null;
52
56 private const int BufferMaxSize = 512;
57
61 private static byte[] buffer = new byte[BufferMaxSize];
62
67 private static byte[] receiveBuffer;
68
69 private static int initialReceiveBufferIndex = 0;
70
74 private static StringBuilder message = new StringBuilder();
75 private static int newLength = 1;
76 private static int packetCounter = 0;
77
81 public delegate void ReadEvent(string msg, byte[] buffer);
82 public static ReadEvent readEvent = null;
83
89 public static bool Open(string host)
90 {
91 return Client.Open(host, defaultPort);
92 }
93
100 public static bool Open(string host, int port)
101 {
102 bool status = true;
103
104 try
105 {
106 client = new TcpClient(host, port);
107
108 stream = client.GetStream();
109
110 // Start reading tcp stream and call "ReadCallback" method when newLength data
111 // will be received
112 // initially, "newLength" is equal to 1, so first call to ReadCallback
113 // will be done after reception of 1 byte.
114
115 // received data are stored in buffer
116 // Next reading will be done in ReadCallback method
117 stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
118 }
119 catch (ArgumentNullException e)
120 {
121 Console.WriteLine("ArgumentNullException: " + e);
122 status = false;
123 }
124 catch (SocketException e)
125 {
126 Console.WriteLine("SocketException: " + e.ToString());
127 status = false;
128 }
129 catch (Exception e)
130 {
131 Console.WriteLine("Unknown Exception: " + e.ToString());
132 status = false;
133 }
134
135 return status;
136 }
137
141 public static void Close()
142 {
143 if (stream != null) stream.Close();
144 if (client != null) client.Close();
145 }
146
151 private static void ReadCallback(IAsyncResult ar)
152 {
153 if (client.Connected)
154 {
155 int bytesRead;
156
157 try
158 {
159 // Termintae read operation, and get number of byte stored in buffer
160 bytesRead = stream.EndRead(ar);
161 }
162 catch (ObjectDisposedException e)
163 {
164 Console.WriteLine("Connection to server dropped: " + e.ToString());
165 return;
166 }
167
168 newLength = 1;
169
170 // if number of byte read is not 0, concatenate string and buffer
171 if (bytesRead > 0)
172 {
173 packetCounter++;
174
175 if (packetCounter >= 3)
176 {
177 //Console.WriteLine("Supplementary packet " + packetCounter);
178 }
179
180 // Append new data to current string (expecting data are ascii)
181 message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
182
183 // Similarly, append received bytes to current buffer
184 if (receiveBuffer == null) receiveBuffer = new byte[bytesRead];
185 else Array.Resize<byte>(ref receiveBuffer, initialReceiveBufferIndex + bytesRead); // resize currrent buffer
186
187 System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead); // and add received data
188 initialReceiveBufferIndex = receiveBuffer.Length; // move last index of current buffer
189 }
190
191 // if it remains received data, prepare for a new reading (get another buffer to append to current one)
192 if (client.Available > 0)
193 {
194 newLength = client.Available;
195 if (newLength > BufferMaxSize) newLength = BufferMaxSize;
196 else newLength = client.Available;
197 }
198 else
199 {
200 // no more data to read, buffer and string can be send to upper level
201 readEvent?.Invoke(message.ToString(), receiveBuffer);
202
203 message.Clear();
204 receiveBuffer = null;
205 initialReceiveBufferIndex = 0;
206 packetCounter = 0;
207 }
208
209 // Prepare for reading new data
210 stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
211 }
212 }
213
219 public static void Write(string mes)
220 {
221 if (client.Connected)
222 {
223 byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
224
225 stream.Write(writeBuffer, 0, mes.Length);
226 }
227 }
228 }
229 }
monitor.Client.buffer
static byte [] buffer
Internal buffer used when reading data from server
Definition: Client.cs:61
monitor.Client.packetCounter
static int packetCounter
Definition: Client.cs:76
monitor.Client.initialReceiveBufferIndex
static int initialReceiveBufferIndex
Definition: Client.cs:69
monitor.Client.defaultPort
const int defaultPort
Default server port number
Definition: Client.cs:41
monitor.Client.client
static TcpClient client
Tcp client object
Definition: Client.cs:46
monitor.Client.Write
static void Write(string mes)
Write a string to server
Definition: Client.cs:219
monitor.Client.receiveBuffer
static byte [] receiveBuffer
buffer containing received message from TCP server Used to concatenate internal buffers into one ...
Definition: Client.cs:67
System
monitor.Client.BufferMaxSize
const int BufferMaxSize
Size of internal buffer used when reading data from server
Definition: Client.cs:56
monitor.Client.stream
static NetworkStream stream
Stream object used for communication
Definition: Client.cs:51
monitor.Client.defaultIP
const string defaultIP
Default server name
Definition: Client.cs:36
monitor.Client.ReadEvent
delegate void ReadEvent(string msg, byte[] buffer)
Callback to send received message to upper level
monitor.Client.message
static StringBuilder message
String containing received message from tcp server
Definition: Client.cs:74
monitor.Client.newLength
static int newLength
Definition: Client.cs:75
monitor.Client.Open
static bool Open(string host, int port)
Open connection to server "host", with port number "port"
Definition: Client.cs:100
monitor
Definition: Client.cs:26
monitor.Client.Open
static bool Open(string host)
Open connection to server "host", on default port number.
Definition: Client.cs:89
monitor.Client
Static class for TCP client
Definition: Client.cs:31
monitor.Client.Close
static void Close()
Close connection to server
Definition: Client.cs:141
monitor.Client.readEvent
static ReadEvent readEvent
Definition: Client.cs:82
monitor.Client.ReadCallback
static void ReadCallback(IAsyncResult ar)
Callback call by stream.BeginRead after reception of newLength data
Definition: Client.cs:151