Client.cs
Go to the documentation of this file.
//
// Client.cs
//
// Author:
// Di MERCURIO Sébastien <dimercur@insa-toulouse.fr>
//
// Copyright (c) 2018 INSA - DGEI
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Net.Sockets;
using System.Text;
namespace monitor
{
public static class Client
{
public const string defaultIP = "localhost";
public const int defaultPort = 4500;
private static TcpClient client = null;
private static NetworkStream stream = null;
private const int BufferMaxSize = 512;
private static byte[] buffer = new byte[BufferMaxSize];
private static byte[] receiveBuffer;
private static int initialReceiveBufferIndex = 0;
private static StringBuilder message = new StringBuilder();
private static int newLength = 1;
private static int packetCounter = 0;
public delegate void ReadEvent(string msg, byte[] buffer);
public static ReadEvent readEvent = null;
public static bool Open(string host)
{
return Client.Open(host, defaultPort);
}
public static bool Open(string host, int port)
{
bool status = true;
try
{
client = new TcpClient(host, port);
stream = client.GetStream();
// Start reading tcp stream and call "ReadCallback" method when newLength data
// will be received
// initially, "newLength" is equal to 1, so first call to ReadCallback
// will be done after reception of 1 byte.
// received data are stored in buffer
// Next reading will be done in ReadCallback method
stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e);
status = false;
}
catch (SocketException e)
{
Console.WriteLine("SocketException: " + e.ToString());
status = false;
}
catch (Exception e)
{
Console.WriteLine("Unknown Exception: " + e.ToString());
status = false;
}
return status;
}
public static void Close()
{
if (stream != null) stream.Close();
if (client != null) client.Close();
}
private static void ReadCallback(IAsyncResult ar)
{
if (client.Connected)
{
int bytesRead;
try
{
// Termintae read operation, and get number of byte stored in buffer
bytesRead = stream.EndRead(ar);
}
catch (ObjectDisposedException e)
{
Console.WriteLine("Connection to server dropped: " + e.ToString());
return;
}
newLength = 1;
// if number of byte read is not 0, concatenate string and buffer
if (bytesRead > 0)
{
packetCounter++;
if (packetCounter >= 3)
{
//Console.WriteLine("Supplementary packet " + packetCounter);
}
// Append new data to current string (expecting data are ascii)
message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
// Similarly, append received bytes to current buffer
if (receiveBuffer == null) receiveBuffer = new byte[bytesRead];
else Array.Resize<byte>(ref receiveBuffer, initialReceiveBufferIndex + bytesRead); // resize currrent buffer
System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead); // and add received data
initialReceiveBufferIndex = receiveBuffer.Length; // move last index of current buffer
}
// if it remains received data, prepare for a new reading (get another buffer to append to current one)
if (client.Available > 0)
{
newLength = client.Available;
if (newLength > BufferMaxSize) newLength = BufferMaxSize;
else newLength = client.Available;
}
else
{
// no more data to read, buffer and string can be send to upper level
readEvent?.Invoke(message.ToString(), receiveBuffer);
message.Clear();
receiveBuffer = null;
initialReceiveBufferIndex = 0;
packetCounter = 0;
}
// Prepare for reading new data
stream.BeginRead(buffer, 0, newLength, new AsyncCallback(ReadCallback), message);
}
}
public static void Write(string mes)
{
if (client.Connected)
{
byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
stream.Write(writeBuffer, 0, mes.Length);
}
}
}
}
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