25 private static TcpClient
client = null;
30 private static NetworkStream
stream = null;
53 private static StringBuilder
message =
new StringBuilder();
60 public delegate
void ReadEvent(
string msg, byte[] buffer);
68 public static bool Open(
string host)
79 public static bool Open(
string host,
int port)
85 client =
new TcpClient(host, port);
87 stream = client.GetStream();
96 stream.BeginRead(buffer, 0, newLength,
new AsyncCallback(
ReadCallback), message);
98 catch (ArgumentNullException e)
100 Console.WriteLine(
"ArgumentNullException: " + e);
103 catch (SocketException e)
105 Console.WriteLine(
"SocketException: " + e.ToString());
110 Console.WriteLine(
"Unknown Exception: " + e.ToString());
122 if (stream != null) stream.Close();
123 if (client != null) client.Close();
132 if (client.Connected)
139 bytesRead = stream.EndRead(ar);
141 catch (ObjectDisposedException e)
143 Console.WriteLine(
"Connection to server dropped: " + e.ToString());
154 if (packetCounter >= 3)
160 message.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
163 if (receiveBuffer == null) receiveBuffer =
new byte[bytesRead];
164 else Array.Resize<byte>(ref
receiveBuffer, initialReceiveBufferIndex + bytesRead);
166 System.Buffer.BlockCopy(buffer, 0, receiveBuffer, initialReceiveBufferIndex, bytesRead);
167 initialReceiveBufferIndex = receiveBuffer.Length;
171 if (client.Available > 0)
173 newLength = client.Available;
175 else newLength = client.Available;
183 receiveBuffer = null;
184 initialReceiveBufferIndex = 0;
189 stream.BeginRead(buffer, 0, newLength,
new AsyncCallback(
ReadCallback), message);
198 public static void Write(
string mes)
200 if (client.Connected)
202 byte[] writeBuffer = Encoding.UTF8.GetBytes(mes);
204 stream.Write(writeBuffer, 0, mes.Length);
static byte [] buffer
Internal buffer used when reading data from server
static int initialReceiveBufferIndex
const int defaultPort
Default server port number
static TcpClient client
Tcp client object
static void Write(string mes)
Write a string to server
static byte [] receiveBuffer
buffer containing received message from TCP server Used to concatenate internal buffers into one ...
const int BufferMaxSize
Size of internal buffer used when reading data from server
static NetworkStream stream
Stream object used for communication
const string defaultIP
Default server name
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
static bool Open(string host, int port)
Open connection to server "host", with port number "port"
static bool Open(string host)
Open connection to server "host", on default port number.
Static class for TCP client
static void Close()
Close connection to server
static ReadEvent readEvent
static void ReadCallback(IAsyncResult ar)
Callback call by stream.BeginRead after reception of newLength data